CSS Specificity
Sometimes two CSS rules try to style the same element in different ways. Specificity is the way the browser decides which rule wins.
p { color: blue; }
.note { color: green; }
#intro { color: red; }
<p id="intro" class="note">What colour am I?</p>
The text is red, because an id selector is stronger than a class selector, and a class selector is stronger than an element selector.
The specificity order
| Strength | Selector type | Example |
|---|---|---|
| Strongest | Inline style | style="color: red" |
| 2 | ID | #intro |
| 3 | Class, attribute, pseudo-class | .note, [type="text"], :hover |
| 4 (weakest) | Element, pseudo-element | p, ::before |
A simple way to count: ID = 100 points, class = 10 points, element = 1 point.
p /* 1 */
.note /* 10 */
p.note /* 11 */
#intro /* 100 */
div #intro p /* 101 */
Same specificity: the last rule wins
p { color: blue; }
p { color: orange; } /* this one wins, it comes later */
!important
Adding !important to a declaration makes it win against normal rules, even inline styles.
p { color: blue !important; }
Note:
Avoid !important. It makes your CSS hard to fix later. If you need it a lot, your selectors need a cleaner plan.
Inheritance
Some properties, like color and font-family, are passed from a parent to its children. Others, like border and margin, are not.
body { color: #333; font-family: Arial, sans-serif; } /* all text inside inherits it */
Summary
- Inline style > id > class > element.
- If the strength is the same, the later rule wins.
- Avoid
!importantand avoid very long selectors. - Next: CSS Colors.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |