且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么CSS中的媒体查询顺序很重要?

更新时间:2023-09-15 23:24:28

这是由CSS设计的层叠样式表。

That's by design of CSS — Cascading Style Sheet.

这意味着,如果你应用两个碰到相同元素的规则,它将选择最后一个被声明的规则,除非第一个规则具有!important marker或更具体(例如 html> body vs body ,后者不太具体)

It means that, if you apply two rules that collide to the same elements, it will choose the last one that was declared, unless the first one has the !important marker or is more specific (e.g. html > body vs just body, the latter is less specific).

因此,给定此CSS

@media (max-width: 600px) {
  body {
    background: red;
  }
}

@media (max-width: 400px) {
  body {
    background: blue;
  }
}

如果浏览器窗口宽350像素,将为蓝色,而使用此CSS

if the browser window is 350 pixels wide, the background will be blue, while with this CSS

@media (max-width: 400px) {
  body {
    background: blue;
  }
}

@media (max-width: 600px) {
  body {
    background: red;
  }
}

和相同的窗口宽度,背景将是红色。

and the same window width, the background will be red. Both rules are indeed matched, but the second one it's the one that is applied because is the last rule.

最后,使用

@media (max-width: 400px) {
  body {
    background: blue !important;
  }
}

@media (max-width: 600px) {
  body {
    background: red;
  }
}

@media (max-width: 400px) {
  html > body {
    background: blue;
  }
}

@media (max-width: 600px) {
  body {
    background: red;
  }
}

背景将是蓝色的窗口)。

the background will be blue (with a 350 pixels wide window).