【问题标题】:Is it possible to nest media queries within media queries?是否可以在媒体查询中嵌套媒体查询?
【发布时间】:2011-12-01 20:52:23
【问题描述】:

这可能吗?这对我来说似乎是一个很好的解决方案,但我不确定它是否会起作用。

@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {

    /* Code for both portrait and landscape */

    @media (orientation:portrait) {

        /* Code for just portrait */

    }

    @media (orientation:landscape) {

        /* Code for just landscape */

    }

}

【问题讨论】:

    标签: css media-queries


    【解决方案1】:

    您应该可以nest @media rules this way in CSS3,但大多数浏览器尚不支持它。详情请见this answer

    您必须完全扩展并重复顶级媒体查询以获取内部规则才能跨浏览器工作(我想 SCSS 处理器会生成类似的东西):

    @media only screen 
    and (min-device-width: 320px) 
    and (max-device-width: 480px) {
        /* Code for both portrait and landscape */
    }
    
    @media only screen 
    and (min-device-width: 320px) 
    and (max-device-width: 480px) 
    and (orientation: portrait) {
    
        /* Code for just portrait */
    
    }
    
    @media only screen 
    and (min-device-width: 320px) 
    and (max-device-width: 480px) 
    and (orientation: landscape) {
    
        /* Code for just landscape */
    
    }
    

    【讨论】:

    【解决方案2】:

    如果你想这样做,最好的方法是在链接标签中使用高级媒体查询,然后在链接表中使用其他查询。

    实际上,尽管大多数人将他们的 CSS 规则从涵盖常见内容的基本表中级联起来,然后在每个媒体规则集中对其进行更改。

    【讨论】:

    • 我喜欢这个想法,因为它在技术上隐含了嵌套。
    【解决方案3】:

    我认为不可能,但如果您使用的是 SASS css 预处理器,您可以编写这种格式。

    示例,您可以复制此代码并粘贴到https://www.sassmeister.com/ - 并观察输出

    SASS

    @media only screen and (max-width: 767px) {
      body{
        color:red;
      }
       @media (orientation:portrait) {
           body{
            color:green;
          }
       }
       @media (orientation:landscape) {
           body{
            color:orange;
          }
       }
    }
    

    输出 CSS

    @media only screen and (max-width: 767px) {
      body {
        color: red;
      }
    }
    @media only screen and (max-width: 767px) and (orientation: portrait) {
      body {
        color: green;
      }
    }
    @media only screen and (max-width: 767px) and (orientation: landscape) {
      body {
        color: orange;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-13
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      • 2019-09-19
      • 2022-01-25
      • 2015-07-18
      • 1970-01-01
      • 2014-02-19
      相关资源
      最近更新 更多