最近,我一直在设计响应速度更快的网站,并且经常使用 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 开头指定的边距值 (margin-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;}
}
如果我对媒体查询的理解是正确的,那么顺序应该不重要,但看起来确实如此。可能是什么原因?
这是 CSS 设计的——层叠样式表。
这意味着,如果您应用两个与相同元素发生冲突的规则,它将选择最后一个声明的规则,除非第一个规则具有!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;
}
}
or
@media (max-width: 400px) {
html > body {
background: blue;
}
}
@media (max-width: 600px) {
body {
background: red;
}
}
背景将为蓝色(窗口宽度为 350 像素)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)