【问题标题】:media-query specificity - why is the largest style used when using max-width media queries?media-query specificity - 为什么使用最大宽度媒体查询时使用最大样式?
【发布时间】:2026-01-24 04:15:01
【问题描述】:

我有以下(简化的)示例代码: (jsbin:http://jsbin.com/cisahilido/1/edit?html,css,output)

SCSS:

.container {
  background: none;
}

@media screen and (max-width: 480px) {
  .container {
    background: red;
  }
}

@media screen and (max-width: 768px) {
    .container {
    background: white;
  }
}

@media screen and (max-width: 1024px) {
    .container {
    background: blue;
  }
}

标记:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div class="container">
    hello!
  </div>
</body>
</html>

现在,当屏幕为 480 像素或更少时,我希望 .container 具有红色背景。但是,它似乎总是有蓝色背景,直到 1024px 断点,它才没有背景。

为什么 max-width 样式会用较大的断点覆盖较小的断点?

【问题讨论】:

    标签: css media-queries css-specificity css-cascade


    【解决方案1】:

    因为 480 小于最后一个 max-width 的 1024。CSS 总是使用最后一个有效值,所以你需要将 max-width 媒体查询从大到小排序才能得到预期的值。

    jsbin

    .container {
        background: none;
    }
    
    @media screen and (max-width: 1024px) {
        .container {
            background: blue;
        }
    }
    
    @media screen and (max-width: 768px) {
        .container {
            background: white;
        }
    }
    
    @media screen and (max-width: 480px) {
        .container {
            background: red;
        }
    }
    

    【讨论】: