处理css层叠性问题,经常使用css权重。下面总结了一些css计算权重步骤。
1.首先看是否选中。若选中了,就以(id的数目,类的数目,标签的数目)来计算权重。以权重大的为准。
2.若没有选中,则权重为0。此时采用“就近原则”。
例如:
(1)选中的例子:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>权重问题</title>
<style type="text/css">
#box1 .b2 p{ /*此处权重为(1,1,1)*/
color: blue;
}
div div #box3 p{ /*此处权重为(1,0,3)*/
color: red;
}
div.b1 div.b2 div.b3 p{ /*此处权重为(0,3,4)*/
color: green;
}
</style>
</head>
<body>
<div id="box1" class="b1">
<div id="box2" class="b2">
<div id="box3" class="b3">
<p>权重计算</p>
</div>
</div>
</div>
</body>
</html>
根据比较权重大小,此处应该是显示蓝色字。如下截图:
(2)未选中的例子:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>权重问题</title>
<style type="text/css">
div p{ /*未选中,权重为0*/
color: red;
}
#box{ /*未选中,权重为0*/
color: blue;
}
</style>
</head>
<body>
<div id="box">
<p id="p1" class="sp1">
<span>权重问题2</span>
</p>
</div>
</body>
</html>
未选中时,权重为0,此时采用就近原则。因为p标签距离span标签更近,故文字显示红色。
(3)选中与未选中混合:
因未选中权重为0,选中的权重始终比未选中的权重大,故此时以权重大的为准。
注意:可以使用“!important”来提高属性的权重,标记了“!important”的属性的权重是最大的。
使用“!important”注意事项:
(1)“!important”提升的是一个属性,而不是一个选择器;
(2)“!important”不能提升继承的属性;
(3)“!important”不影响“就近原则”。
实际开发中一般不使用“!important”!