如前所述,样式优先级是按特异性排序的。这是一个简单的演示来说明。
HTML
<div class="container">
<p class="nested-p">Something</p>
</div>
<div class="container">
<p class="nested-p2">Something</p>
</div>
CSS
.nested-p {
background: red; /* yeah right, this isn't going to be applied */
}
/* more specific */
.container .nested-p2 {
background: green;
}
/* less specific */
.container p {
font-size: 2em; /* will be applied to both nested p*/
background: blue; /* only applied to the first because it is less specific than the previous declaration */
}
/* even less specific */
.nested-p2 {
background: blue; /* will not be applied */
font-size: 4em; /* will be applied, because it's not applied in the more specific class */
}
演示