结合两个媒体查询

时间:2018-04-01 15:16:51

标签: css media-queries

我正在尝试测试媒体查询。我希望当宽度小于&lt; = 600且高度<= 400像素时,背景颜色呈现蓝色。

我尝试过使用:

  1. @media only screen and (max-width: 600px) and (max-height: 400px)
  2. @media only screen and (max-width: 600px) and only screen (max-height: 400px)
  3. @media only screen and (max-width: 600px and max-height: 400px)
  4. @media only screen and (max-width: 600px), (max-height: 400px)
  5. 但是1-3没有做任何事情,如果任何一个陈述都是真的,4渲染背景为蓝色。每当我谷歌我想做什么,我看到答案,说#4等解决方案。 (例如this SO answer.)这不是我想要的。

    我通过使用下面的嵌套查询来实现它。 这是做我想做的最好/唯一的方法还是有更清洁的解决方案?

    @media only screen and (max-width: 600px) {
        @media only screen and (max-height: 400px) {
            body {
                background-color: blue;
            }
        }
    }
    

1 个答案:

答案 0 :(得分:0)

最干净的方式是你的第一个提议的解决方案 1 实际上运行正常 - 请参阅下面的代码段(扩展到完整大小):

div {
  background-color: blue;
  height: 300px;
}

@media only screen and (max-width: 600px) and (max-height: 400px) {

  div {
    background-color: red;
  }


}
<div></div>

1 @media only screen and (max-width: 600px) and (max-height: 400px)