【问题标题】:Media query properties being overwriiten by other breakpoints媒体查询属性被其他断点覆盖
【发布时间】:2019-05-19 12:46:48
【问题描述】:

我需要根据视口的宽度应用一些样式。为此,我编写了一些媒体查询,但在运行它们时,我发现较小的媒体查询被覆盖了。

代码示例:https://codepen.io/anon/pen/joLVGZ

HTML

<div>
  hello
</div>

CSS

div {
  height: 200px;
}
/*
 * Less than 576px
*/
@media screen and (max-width: 576px) {
  div {
    background-color: red;
  }
}

/*
 * Less than 768px
 */
@media screen and (max-width: 768px) {
  div {
    background-color: green;
  }
}

/*
 * Less than 992px 
*/
@media screen and (max-width: 992px) {
  div {
    background-color: blue;
  }
}

/*
 * Less than 1200px
*/
@media screen and (max-width: 1200px) {
  div {
    background-color: yellow;
  }
}

/*
Greator than 1200px
*/
@media (min-width: 1200px) {
  div {
    background-color: grey;
  }
}

在示例中,我尝试更改浏览器大小,但设置为 992 像素(黄色)的背景颜色会覆盖其他断点,并且对于所有其他较小的大小,颜色仍为黄色。

如何确保样式不会覆盖其他样式?我的媒体查询是否写错了?

【问题讨论】:

    标签: css responsive-design media-queries


    【解决方案1】:

    只需颠倒媒体查询的顺序即可。你拥有它们的方式,倒数第二个会覆盖所有以前的,因为max-width: 1200px 适用于 1200 像素以下的所有内容。

    【讨论】:

      【解决方案2】:

      只需更改@media的顺序即可:

      div {
        height: 200px
      }
      /* More than 1200px */
      @media (min-width: 1200px) {
        div {
          background-color: grey;
        }
      }
      
      /* Less than 1200px */
      @media screen and (max-width: 1200px) {
        div {
          background-color: yellow;
        }
      }
      /* Less than 992px */
      @media screen and (max-width: 992px) { 
        div {
          background-color: blue;
        }
      }
      /* Less than 768px */
      @media screen and (max-width: 768px) {
        div {
          background-color: green;
        }
      }
      /* Less than 576px */
      @media screen and (max-width: 576px) {
        div {
          background-color: red;
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-02-10
        • 2020-06-18
        • 2020-02-15
        • 2017-01-14
        • 2022-11-14
        • 2012-07-10
        • 2014-12-07
        • 2019-05-07
        • 1970-01-01
        相关资源
        最近更新 更多