我们现在已经学过了很多的选择器,也就是说我们有很多种方法从HTML中找到某个元素,那么就会有一个问题:如果我通过不用的选择器找到了相同的一个元素,并且设置了不同的样式,那么浏览器究竟应该按照哪一个样式渲染呢?也就是不同的选择器它们的优先级是怎样的呢?
是先来后到呢还是后来居上呢?统统不是,它是按照下面的选择器的权重规则来决定的。

<!DOCTYPE html><html><head><title>选择器权重</title><style type="text/css">/*数选择器的数量: id选择器 类选择器 标签选择器*//*0 1 0*/.b{color: purple;}/*0 0 3*/html body div{color: red;}/*1 0 0*/#b{color: orange;}</style></head><body><div>a</div><div class="b" id="b" style="color: green;">b</div></body></html>
<!DOCTYPE html><html><head><title>css选择器权重深入</title><style type="text/css">/*数选择器的数量: id选择器 类选择器 标签选择器*//* 0 0 3*/div div p{/*color: yellow;*/}/*0 0 1*/p{color: gray;}/*0 1 0*/.active{/*color: purple;*/}/*0 1 1*/div .active{/*color: black;*/}/*0 1 1*/div div .active{/*color: blue;*/}/*1 2 0*/.wrap1 #box2 .active{/*color: green;*/}/*2 0 1*/#box1 #box2 p{/*color: red;*/}/*继承来的属性 它的权重非常低 0*/#box1 #box2 #box3{color: orange;}.container{color: orange;font-size: 14px;}.container ul li {color: #000;font-size: 16px;}</style></head><body><div class="wrap1" id="box1"><div class="wrap2" id="box2"><div class="wrap3" id="box3"><p class="active">MJJ是什么颜色</p></div></div></div><div class="container"><ul><li>小米手机</li></ul></div></body></html>
注意:
还有一种不讲道理的!import方式来强制让样式生效,但是不推荐使用。因为大量使用!import的代码是无法维护的。一般用于修改全局的CSS
<!DOCTYPE html><html><head><title>!important讲解</title><style type="text/css">#a{color: green !important;}div{color: purple !important;}</style></head><body><div class="a" id="a">a</div></body></html>
