是否可以在媒体查询中嵌套媒体查询?

时间:2011-10-05 22:03:30

标签: css css3 media-queries

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

@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 */

    }

}

3 个答案:

答案 0 :(得分:29)

您应该能够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 */

}

答案 1 :(得分:2)

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

在实践中,尽管大多数人从基础表中将CSS规则级联起来,然后在每个媒体规则集中对其进行更改。

答案 2 :(得分:0)

I think not possible but you can write this format If you are using SASS css pre-processor.

example , you can copy this code and paste to https://www.sassmeister.com/ -and watch the output

SASS

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

Output 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;
  }
}