最近,我一直在设计更具响应性的网站,我也经常使用CSS媒体查询。我注意到的一种模式是定义媒体查询的顺序实际上很重要。我没有在每个浏览器上测试它,只是在Chrome上测试。对这种行为有什么解释吗?有时,当您的站点不能正常工作,并且您不确定是查询还是查询的编写顺序时,您会感到沮丧。
下面是一个例子:
HTML
<body>
<div class="one"><h1>Welcome to my website</h1></div>
<div class="two"><a href="#">Contact us</a></div>
</body>
CSS:
body{
font-size:1em; /* 16px */
}
.two{margin-top:2em;}
/* Media Queries */
@media (max-width: 480px) {
.body{font-size: 0.938em;}
}
/* iphone */
@media only screen and (-webkit-min-device-pixel-ratio: 2) {
body {font-size: 0.938em;}
}
/*if greater than 1280x800*/
@media (min-width: 1200px) {
.two{margin-top:8em;}
}
/*1024x600*/
@media (max-height: 600px) {
.two{margin-top:4em;}
}
/*1920x1024*/
@media (min-height: 1020px) {
.two{margin-top:9em;}
}
/*1366x768*/
@media (min-height: 750px) and (max-height: 770px) {
.two{margin-top:7em;}
}
但是,如果我在最后编写了1024x600的查询,浏览器将忽略它,并应用CSS开头指定的边距值( wrote top:2em)。
/* Media Queries - Re-arranged version */
@media (max-width: 480px) {
.body{font-size: 0.938em;}
}
/* iphone */
@media only screen and (-webkit-min-device-pixel-ratio: 2) {
body {font-size: 0.938em;}
}
/*if greater than 1280x800*/
@media (min-width: 1200px) {
.two{margin-top:8em;}
}
/*1920x1024*/
@media (min-height: 1020px) {
.two{margin-top:9em;}
}
/*1366x768*/
@media (min-height: 750px) and (max-height: 770px) {
.two{margin-top:7em;}
}
/*1024x600*/
@media (max-height: 600px) {
.two{margin-top:4em;}
}
如果我对媒体查询的理解是正确的,那么顺序应该不重要,但看起来很重要。可能的原因是什么?
发布于 2012-01-10 00:58:47
这是通过CSS - Cascading样式表设计的。
这意味着,如果您将两个冲突的规则应用于相同的元素,它将选择最后一个已声明的规则,除非第一个规则具有!important
标记或更具体(例如,html > body
与仅body
,后者不太具体)。
因此,给定这个CSS
@media (max-width: 600px) {
body {
background: red;
}
}
@media (max-width: 400px) {
body {
background: blue;
}
}
如果浏览器窗口的宽度为350像素,则背景将为蓝色,而使用此CSS时
@media (max-width: 400px) {
body {
background: blue;
}
}
@media (max-width: 600px) {
body {
background: red;
}
}
和相同的窗口宽度,背景将是红色。这两个规则确实是匹配的,但第二个规则是应用的,因为它是最后一个规则。
最后,使用
@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;
}
}
背景将为蓝色(具有350像素宽的窗口)。
发布于 2014-11-06 23:58:27
或者,您可以只将最小宽度添加到更大的媒体查询中,而不考虑顺序。
@media (min-width: 400.1px) and (max-width: 600px) {
body {
background: red;
}
}
@media (max-width: 400px) {
body {
background: blue;
}
}
使用此代码,以任何顺序,对于宽度为400.1px-600px的分辨率,背景颜色将始终为红色;对于宽度为400px或更小的分辨率,背景颜色将始终为蓝色。
https://stackoverflow.com/questions/8790321
复制相似问题