Amy Westlake

< Back to blog

Style Specificity in CSS

Note: I wrote this article as part of a job application, it is aimed at beginners.

Specificity describes the way the browser decides which styles to give an element on a web page. Specificity matches your CSS selectors to your HTML elements, decides which styles takes priority and applies it.

How does it work?

First the browser will look to see if you are targeting your styles with an ID as an ID will always take priority over a Class. If no ID is being used it will count the number of Classes used in your styling, a style declaration with four Classes will overwrite a declaration with just one Class. What happens if two style declarations have the same specificity?

The declaration closest to the HTML element will take priority. If you set a p font-color in the first few lines of your CSS file but then set a different font-color near the end of your file the declaration at the end of the document will be used. If you’ve got multiple stylesheets with the same style declarations in the stylesheet closest to the HTML element will take priority over the one before it.

It’s not good practice but you can override any styles in a stylesheet by adding your style declarations inline in the HTML document. Inline styles have the highest specificity.

Overriding Specificity

If you’ve got clashing styles and want to override the default specificity levels you can do so with !important in your stylesheet. Let’s use the example from earlier, put !important on the first p font-color and the second p font-color will be ignored.

Avoiding Specificity Issues

You can avoid specificity issues in your CSS by giving your HTML elements descriptive classes and not nesting your styles. This will make your code much easier to maintain when it comes to making styling updates in the future.

< Back to blog