CSS precedence

What is CSS precedence

When you have multiple CSS codes targeting the same element on your page, you need to tell the website what CSS has the priority over other CSS codes.

Imagine if you wanted to customise something on the page. You inspect element, grab the CSS code and copy it, paste it in the theme options, or your child theme's CSS, make your changes and save - but no luck! Nothing has been changed, and the default CSS still has the lead.

Or, what if the default code already uses "!important" rule? 

Find out how to make your new CSS override the one that's already there, no matter what.


How it works

While a lot can be said on the topic, I'll keep it as short as I think it should be, and leave some links down below, for all of you nerds who want to learn further.


The important rule

The easiest way to override an already existing CSS is by using the "!important" rule. It's super easy to apply this rule, and here's an example that will illustrate that:

Imagine if we had this CSS by default.

a {

color: #fff;

}

To override it, you can simply add "!important" rule, like this:

a {

color: #fff !important;

}

This normally works great, however, you can often times notice that this rule is already applied. To see what else you can do, read below.


More CSS selectors

The more CSS selectors you add, the more priority your CSS is going to have! For all of you who are not sure what a CSS selector is, read this quickly https://www.w3schools.com/cssref/css_selectors.asp and pretend that you already knew that.

Now, a useful example. If you had this:

a {

color: #fff !important;

}

You could override it by adding just one additional selector. For example:

#my-section a {

color: #fff !important;

}

To override even that, just add a new selector:

#some-other-ID #my-section a {

color: #fff !important;

}

And so on. Of course, you can't add ANY selectors, but it has to be real elements from your page, that are parent to the element you are targeting.

IDs and Classes

I would finish by saying that an ID has more precedence than a class, and a class has more precedence than just an HTML selector. They actually have something like precedence points:

p - 1

.class - 10

#id - 100


The more points your CSS has, more precedence it is going to have too. So, instead adding 20 HTML selectors, try with 1 or two IDs, that will save you some time!


Useful resources

https://www.w3schools.com/css/css_specificity.asp

https://css-tricks.com/specifics-on-css-specificity/

https://www.htmldog.com/guides/css/intermediate/specificity/

Still need help? Contact Us Contact Us