CSS Style Selectors ( Order of Precedence )

CSS Style Selectors ( Order of Precedence )

In this post, we will highlight basic ways of styling HTML elements and their order of implementation. There exist various ways to style HTML elements with selectors that you might have come across but in case of conflicts whereby a single element is styled with different selectors, how do you know which styling will take precedence?

Take a seat and let's explore this together.

Here is a basic HTML we will work with in this tutorial

and this is the style for the same HTML shown earlier. Let's give the h1 tags a blue color.

As observed, we see that all h1 elements are now colored blue.

How about we style the second element green color using the class selector

Wait for a second, the class 'header' also points to an h1 tag element previously styled, there is a conflict in the styles now. Yes! there absolutely is a conflict, but let's allow CSS to do its thing.

Here is the result of our updated stylesheet.

What do you observe, the class 'header' selector overwrites the style of the tag 'h1' selector and changes the color to green. How about we introduce another conflict and style the second 'h1' element using the 'id' selector. Now our style becomes what we have below.

Let's see what we now have

Things are now getting interesting, you observe that the id selector 'head' overwrites the style of the class 'header' selector. Let's break this down. The class selector 'header' > tag selector 'h1', and the 'id' selector takes precedence over the class selector. So we can deduce that in the order of style selections, the id comes first followed by the class selector followed by the tag selector. Using a bit of maths we could say id > class > tag.

This ain't much but it could save you from a headache when figuring out conflicts in your CSS styles and also comes in handy when adding exclusive styles to specific elements.

Thanks for your time.