css样式优先级机制

    xiaoxiao2021-03-26  23

    对css选择器不熟悉的建议先看看w3school

    一、权值不同时

    样式类型权重值style内联样式(标签内部)1000ID选择器0100类选择器,属性选择器,伪类0010元素选择器,伪元素0001

    下面我们就可以根据上表的权值来计算和比较优先级

    选择器权重值div span {color:blue}1+1=2div .hot {color:yellow}10+1=11#wrap span {color:black}100+1=101#wrap .hot {color:red}100+10=110

    1、根据上面的权重值计算,我们可以知道最终样式为color:red。

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> div span {color:blue;} div .hot {color:yellow;} #wrap span {color:black;} #wrap .hot {color:red;} </style> </head> <body> <div id="wrap" class="div1"> <span class="hot"> hhhhhhhhhhhhhhhhh </span> </div> </body> </html>

    运行结果确实为红色:

    注意一下:

    虽然理论上优先级是按上面的权值计算,但是那只是基于同级上的比较。(11个元素选择器级别比不上1个类选择器,其余同理)

    当然,还有比style行间样式优先级更高的是javascript写的样式,即js能修改掉css中的样式,但有一个是例外,那就是css样式中加了!important 。

    2、还是上面的栗子,首先看一下js修改css样式:

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> div span {color:blue;} div .hot {color:yellow;} #wrap span {color:black;} #wrap .hot {color:red;} </style> <script> window.onload = function () { // 修改span里面字体颜色为粉红色 var oHot = document.getElementsByTagName('span')[0]; oHot.style.color = 'pink'; } </script> </head> <body> <div id="wrap" class="div1"> <span class="hot"> hhhhhhhhhhhhhhhhh </span> </div> </body> </html>

    运行结果,文字变成了粉红色:

    3、!important具有最高的优先级,当给选择器中加了!important,js是无法修改的。现在试试给权值最小的div span加上!important (需要提一下:IE6的渲染引擎不认识!important,解析时会自动忽略)

    div span {color:blue; color:orange!important;}

    结果字体是橘色的

    4、继承的样式权值很小,可以看做0或者接近0

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> div .hot {color: blue;} div.div1 {color:yellow;} </style> </head> <body> <div class="div1"> <span class="hot"> hhhhhhhhhhhhhhhhh </span> </div> </body> </html>

    这里结果为蓝色


    二、权值相同时

    一般来说,内联样式表(标签内部)> 内部样式表(当前文件中)> 外部样式表(外部文件中)。但是如果外部样式放在内部样式后面,那么外部样式将覆盖内部样式。 综上我们可以用“就近原则”来说明权值相同时,靠近元素的样式级别优先

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> div{ width: 100px; height: 100px;; } .div1 {background-color:red;} .div2 {background-color: blue;} </style> </head> <body> <div class="div1"></div> <hr/> <div class="div2"></div> <hr/> <div class="div1 div2"></div> <hr/> <div class="div2 div1"></div> <hr/> </body> </html>

    .div2在.div1后面,会覆盖掉前面的样式。但是注意,这个顺序并不是指class里面的先后顺序。我们可以看到第四个div依然是蓝色


    综上

    每个选择器都有权值,权值越大越优先继承的样式优先级低于自身指定样式!important优先级最高权值相同时,靠近元素的样式优先级高(没有js参与)
    转载请注明原文地址: https://ju.6miu.com/read-350372.html

    最新回复(0)