媒体查询特异性 - 为什么在使用最大宽度媒体查询时使用最大样式?
media-query specificity - why is the largest style used when using max-width media queries?
我有以下(简化的)示例代码:
( 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 断点,然后它就没有背景了。
为什么最大宽度样式会用较大的断点覆盖较小的断点?
因为 480 小于最后一个 max-width 1024。CSS 总是使用最后一个有效值,所以您需要将 max-width 媒体查询从大到小排序以获得预期值。
.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;
}
}
我有以下(简化的)示例代码: ( 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 断点,然后它就没有背景了。
为什么最大宽度样式会用较大的断点覆盖较小的断点?
因为 480 小于最后一个 max-width 1024。CSS 总是使用最后一个有效值,所以您需要将 max-width 媒体查询从大到小排序以获得预期值。
.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;
}
}