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

StrengthSelector typeExample
StrongestInline stylestyle="color: red"
2ID#intro
3Class, attribute, pseudo-class.note, [type="text"], :hover
4 (weakest)Element, pseudo-elementp, ::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 !important and avoid very long selectors.
  • Next: CSS Colors.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is the CSS class selector?
What is grouping in CSS and what is it used for?
What are child selectors in CSS?
What is the difference between id and class selector in CSS?
What is specificity in CSS?
What does !important do in CSS?
What are pseudo-classes and pseudo-elements in CSS?