What is the order of precedence for CSS?
Here's a compilation of CSS styling order in a diagram, on which CSS rules has higher priority and take precedence over the rest:
Disclaimer: My team and I worked this piece out together with a blog post (https://vecta.io/blog/definitive-guide-to-css-styling-order) which I think will come in handy to all front-end developers.
There are several rules ( applied in this order ) :
- inline css ( html style attribute ) overrides css rules in style tag and css file
- a more specific selector takes precedence over a less specific one
- rules that appear later in the code override earlier rules if both have the same specificity.
- A css rule with
!important
always takes precedence.
In your case its rule 3 that applies.
Specificity for single selectors from highest to lowest:
- ids (example:
#main
selects<div id="main">
) - classes (ex.:
.myclass
), attribute selectors (ex.:[href=^https:]
) and pseudo-classes (ex.::hover
) - elements (ex.:
div
) and pseudo-elements (ex.:::before
)
To compare the specificity of two combined selectors, compare the number of occurences of single selectors of each of the specificity groups above.
Example: compare #nav ul li a:hover
to #nav ul li.active a::after
- count the number of id selectors: there is one for each (
#nav
) - count the number of class selectors: there is one for each (
:hover
and.active
) - count the number of element selectors: there are 3 (
ul li a
) for the first and 4 for the second (ul li a ::after
), thus the second combined selector is more specific.
A good article about css selector specificity.