总结
- 在选择器优先级相同的情况下,媒体查询中的选择器比外面的选择器的优先级要高
- 如果优先级不同,则媒体查询不会生效,仍遵循原有的选择器优先级规则
选择器优先级不同
参考:https://blog.csdn.net/qq_45279180/article/details/110287811
原博主在写响应式页面的时候发现了个问题,他写的页面是三栏式布局,将内容盒子分成了左右两个盒子,以下代码是对内容盒子中右盒子设置的样式,并通过媒体查询实现响应式后左后盒子不再左右分布而是上下分布:
.content .right-box {
width: 240px;
float: right;
}
@media screen and (max-width:980px) {
.right-box{
float: none;
}
}
但是,预期的效果并没有发生,后来他在控制台发现设置的 float:none; 并没有生效,这时候他想到可能是选择器的权重问题,于是改成了下面的代码:
.content .right-box{
float: none;
}
此时 float:none; 生效了,事实证明确实是选择器权重的原因。
以上例子中,原博主起先以为是当媒体查询生效后,之前的样式就会失效,然后使用媒体查询中的样式,但是并不是这样的。如果选择器优先级不同,则媒体查询不会生效,仍遵循原有的选择器优先级规则。在第一段代码中,他对右边盒子设置浮动的时候选择器权重是20,而媒体查询中的针对右边盒子的选择器的权重是10,虽然媒体查询中的选择器优先级会高于外面的选择器,但是由于权重不相等,媒体查询不生效,因此设置的 float:none; 也没有生效。
选择器优先级相同
参考:https://www.runoob.com/css/css-rwd-mediaqueries.html
优先级:属性选择器 = 类选择器,因此以下媒体查询生效。
CSS代码:
/* For mobile phones: */
[class*="col-"] {
width: 100%;
}
@media only screen and (min-width: 600px) {
/* For tablets: */
.col-m-1 {width: 8.33%;}
.col-m-2 {width: 16.66%;}
.col-m-3 {width: 25%;}
.col-m-4 {width: 33.33%;}
.col-m-5 {width: 41.66%;}
.col-m-6 {width: 50%;}
.col-m-7 {width: 58.33%;}
.col-m-8 {width: 66.66%;}
.col-m-9 {width: 75%;}
.col-m-10 {width: 83.33%;}
.col-m-11 {width: 91.66%;}
.col-m-12 {width: 100%;}
}
@media only screen and (min-width: 768px) {
/* For desktop: */
.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}
}
HTML代码:
<div class="row">
<div class="col-3 col-m-3 menu">
<ul>
<li>The Flight</li>
<li>The City</li>
<li>The Island</li>
<li>The Food</li>
</ul>
</div>
<div class="col-6 col-m-9">
<h1>The City</h1>
<p>Chania is the capital of the Chania region on the island of Crete. The city can be divided in two parts, the old town and the modern city.</p>
</div>
<div class="col-3 col-m-12">
<div class="aside">
<h2>What?</h2>
<p>Chania is a city on the island of Crete.</p>
<h2>Where?</h2>
<p>Crete is a Greek island in the Mediterranean Sea.</p>
<h2>How?</h2>
<p>You can reach Chania airport from all over Europe.</p>
</div>
</div>
</div>