CSS Specificity

Scott
2 min readFeb 11, 2020

--

When there are contradicting styles in your project, the css interpreter chooses the styles which were defined with higher specificity. For example, when Bootstrap sets the background-color of the body, and you therefore can’t easily set the body background color.

Specificities are compared by comparing four components in order: the style that has !important is more specific, if both the styles have !important properties,

then the specificity with a larger A value is more specific; if the two A values are tied, then the specificity with a larger B value is more specific; if the two B values are also tied, then the specificity with a larger C value is more specific; if all the values are tied, the two specificities are equal.

If there is a tie, then the compiler overrides the prior style, so whichever was executed last breaks the tie.

  • !important overrides other specificities.
  • A = number of matching ID selectors
  • B = number of class selectors, attributes selectors, and pseudo-classes
  • C = count the number of type selectors and pseudo-elements
  • ignore the universal selector

Examples:

  1. What color background will the element have?
<div class="one two three four">Hi</div>.one .two .three {
background-color: purple;
}
.four {
background-color: green;
}

2. What color will the background have?

<div class="one two three four">Hi</div>.one .two .three {
background-color: purple;
}
.four {
background-color: green !important;
}

3. What color will the background have?

<div class="one two three" id="four">Hi</div>.one .two .three {
background-color: purple;
}
#four {
background-color: green;
}

4. What color will the background be?

<div class="one two">Hi</div>.one {
background-color: red;
}
.two {
background-color: orange;
}

5. What color will the body be? (tricky)

// In the head we are importing bootstrap:  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
body {
background-color: green;
}

6.

<p class="one">Hi</p>.one {
background-color: red;
}
p {
background-color: orange;
}

Answers:

  1. purple
  2. green
  3. green
  4. orange
  5. white
  6. red

--

--

No responses yet