【问题标题】:How to use particular CSS styles based on screen size / device如何根据屏幕尺寸/设备使用特定的 CSS 样式
【发布时间】:2014-01-31 07:05:21
【问题描述】:

Bootstrap 3 在响应式实用程序中有很好的 CSS 类,允许我根据屏幕分辨率隐藏或显示一些块 http://getbootstrap.com/css/#responsive-utilities-classes

我在 CSS 文件中有一些样式规则,我想根据屏幕分辨率应用或不应用这些规则。

我该怎么做?

我将在生产部署中将我的所有 CSS 文件最小化到一个文件中,但是如果没有其他解决方案,除了为不同的屏幕分辨率设置单独的 CSS 文件之外,这可以避免。

【问题讨论】:

    标签: css twitter-bootstrap twitter-bootstrap-3


    【解决方案1】:

    @media 查询服务于这个目的。这是一个例子:

    @media only screen and (max-width: 991px) and (min-width: 769px){
     /* CSS that should be displayed if width is equal to or less than 991px and larger 
      than 768px goes here */
    }
    
    @media only screen and (max-width: 991px){
     /* CSS that should be displayed if width is equal to or less than 991px goes here */
    }
    

    【讨论】:

      【解决方案2】:

      我创建了一个小 javascript 工具来设置屏幕大小的元素样式,而无需使用媒体查询或重新编译引导 css:

      https://github.com/Heras/Responsive-Breakpoints

      只需将responsive-breakpoints 类添加到任何元素,它就会自动将xs sm md lg xl 类添加到这些元素。

      演示:https://codepen.io/HerasHackwork/pen/rGGNEK

      【讨论】:

        【解决方案3】:

        检测是自动的。您必须指定每种屏幕分辨率可以使用的 css:

        /* for all screens, use 14px font size */
        body {  
            font-size: 14px;    
        }
        /* responsive, form small screens, use 13px font size */
        @media (max-width: 479px) {
            body {
                font-size: 13px;
            }
        }
        

        【讨论】:

          【解决方案4】:

          为什么不使用 @media-queries? 这些都是为这个确切的目的而设计的。 你也可以用 jQuery 来做这件事,但在我的书中这是最后的手段。

          var s = document.createElement("script");
          
          //Check if viewport is smaller than 768 pixels
          if(window.innerWidth < 768) {
              s.type = "text/javascript";
              s.src = "http://www.example.com/public/assets/css1";
          }else { //Else we have a larger screen
              s.type = "text/javascript";
              s.src = "http://www.example.com/public/assets/css2";
          }
          
          $(function(){
              $("head").append(s); //Inject stylesheet
          })
          

          【讨论】:

            【解决方案5】:

            使用@media queries。他们服务于这个确切的目的。以下是它们如何工作的示例:

            @media (max-width: 800px) {
              /* CSS that should be displayed if width is equal to or less than 800px goes here */
            }
            

            这仅适用于宽度等于或小于 800 像素的设备。

            Mozilla Developer Network 上阅读有关媒体查询的更多信息。

            【讨论】:

            • 虽然 media 在 HTML 中使用以包含基于 media 规则的不同 CSS 文件。感谢您指出它也可以在 CSS 中使用。
            • 如果你打开 bootstrap.css 文件,这正是他们所做的
            猜你喜欢
            • 2016-06-26
            • 1970-01-01
            • 1970-01-01
            • 2023-03-17
            • 2019-04-27
            • 2015-08-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多