Web Technology Basics
<style>
#main p { color: red; }
.content p { color: green; }
p.note { color: blue; }
</style>
<div id="main" class="content">
<p class="note">Hello</p>
</div>Assume there are no other style specifications. In the HTML above, which of the following is the color of the text "Hello"?
- ARed
- BGreen
- CBlue
Show answer and explanation
Answer: A. Red
When several rules apply to the same element, the rule whose selector has the higher specificity wins. Specificity is compared as the tuple (number of IDs, number of classes, attributes and pseudo-classes, number of elements): #main p is (1, 0, 1), while .content p and p.note are both (0, 1, 1), so the red of #main p, which contains an ID, is used. Between rules of equal specificity, the one written later wins. A declaration written directly in the style attribute, or one marked !important, takes precedence over these.
- A. Correct. #main p, which contains an ID, has the highest specificity, (1, 0, 1).
- B. The specificity of .content p is (0, 1, 1), lower than the rule containing an ID. It is also written before p.note, which has the same specificity.
- C. p.note is written last, but its specificity (0, 1, 1) is lower than the rule containing an ID, so it is not used. Without the ID rule, the text would be blue.