What is CSS specificity, and how to avoid headaches.

·

2 min read

Selector specificity in CSS is what will determine what styles are applied in the event of a conflict in styles.

An example would be if you had a paragraph and wanted it to be red. You applied color: red using a type selector (p), but you also applied a class to your p tag and then added a class selector with the color property blue.

/* Type selector (lower specificity) */
p {
  color: red;
}

/* Class selector (higher specificity) */
.highlight {
  color: blue; /* This will be applied */
}

Specificity would take over here; your text would be blue because of the hierarchy of selectors.

The same would happen if you doubled up on different selector types (ID, class, and so on). It all comes down to a sum of values for each selector type.

Which is why you need to be careful. Some specifics can complicate specificity.

These are inline CSS styles and the important flag on a CSS declaration.

Inline will override anything in your external file, regardless of its specificity. It will be higher. E.g., if your p tag had an online style saying it should be orange. Then it will be orange, regardless of what you try in your external CSS. The other is true; if you added an important flag to blue on your p class selector, then your text would be blue because the important flag would override the inline CSS.

<p style="color: orange;">This text will be orange, overriding the external stylesheet.</p>
p {
  color: blue;
}

You should be very careful when using the important flag. If, for example, you had a third declaration block with an ID on your p tag and added a color declaration of yellow and the important flag to that, then that would win and your text would be yellow. It's why you should always keep in mind specificity when writing CSS, as well as limiting inline styles and being wary of using the important flag; it can cause a lot of frustrating moments trying to debug.

.special {
  color: blue;
}

/* Importance flag overrides other styles */
p.special {
  color: yellow !important; /* This will be applied */
}

Things to keep in mind to prevent headaches: In your CSS, it's best to keep in mind the simple idea of using CSS as it was designed. Work with the cascade. Keep your specificity low and follow a top-to-bottom hierarchy.

Stay away from inline styles and the important tag.

Keeping all this in mind will reduce the headaches you could have with CSS.