一、层叠
选择器在层叠中取胜的三要素:
1.重要性(Importance):
一条总是优先于其他的规则:!important。但是不建议使用,容易出问题。
2.专用型(Specificity):
选择器 | 千位 | 百位 | 十位 | 个位 | 合计值 |
---|---|---|---|---|---|
h1 | 0 | 0 | 0 | 1 | 0001 |
#indentifier | 0 | 1 | 0 | 0 | 0100 |
h1 + p::first-letter | 0 | 0 | 0 | 3 | 0003 |
li > a[href*="zh-CN"] > .inline-warning | 0 | 0 | 2 | 2 | 0022 |
没有选择器, 规则在一个元素的 <style> 属性里 | 1 | 0 | 0 | 0 | 1000 |
大致意思为:
1)写在style里的样式站比重最大,1000;
2)id选择器所选择的样式,比重100;
3)li>a[href*="zh-CN"]>.inline-warning这种,比重22;
4)h1+p::first-letter这种,比重3;
5)单独的标签选择器,比重1;
当同一个属性在多个CSS组合选择器中存在时,根据比重和决定出用哪一种样式,如下:
HTML:
<div id="outer" class="container">
<div id="inner" class="container">
<ul>
<li class="nav"><a href="#">One</a></li>
<li class="nav"><a href="#">Two</a></li>
</ul>
</div>
</div>
style:(注释中给出了比重和)
/* specificity: 0101 */
#outer a {
background-color: red;
}
/* specificity: 0201 */
#outer #inner a {
background-color: blue;
}
/* specificity: 0104 */
#outer div ul li a {
color: yellow;
}
/* specificity: 0113 */
#outer div ul .nav a {
color: white;
}
/* specificity: 0024 */
div div li:nth-child(2) a:hover {
border: 10px solid black;
}
/* specificity: 0023 */
div li:nth-child(2) a:hover {
border: 10px dashed black;
}
/* specificity: 0033 */
div div .nav:nth-child(2) a:hover {
border: 10px double black;
}
a {
display: inline-block;
line-height: 40px;
font-size: 20px;
text-decoration: none;
text-align: center;
width: 200px;
margin-bottom: 10px;
}
ul {
padding: 0;
}
li {
list-style-type: none;
}
3.源代码次序(Source order):
同样的专用型级别,那么后者样式会胜于前者。
p {
color: blue;
}
/* This rule will win over the first one */
p {
color: red;
}
二、继承
1.控制继承
inherit
: 该值将应用到选定元素的属性值设置为与其父元素一样。initial
:该值将应用到选定元素的属性值设置为与浏览器默认样式表中该元素设置的值一样。如果浏览器默认样式表中没有设置值,并且该属性是自然继承的,那么该属性值就被设置为inherit
。unset
:该值将属性重置为其自然值,即如果属性是自然继承的,那么它就表现得像inherit
,否则就是表现得像initial
。revert
:如果当前的节点没有应用任何样式,则将该属性恢复到它所拥有的值。换句话说,属性值被设置成自定义样式所定义的属性(如果被设置), 否则属性值被设置成用户代理的默认样式。