Basic CSS precedence of Selectors

The Basics

CSS is applied to HTML elements by way of selectors, and sets the elements’ properties to the values in the CSS class.

CSS Syntax layout
CSS Syntax – image from W3 Schools

Style Inheritance

If an element has no style set, it inherits its style from its parent, i.e. if the body element has a font set, that font will be used by all child elements under it, unless a child element has a font setting of its own.
Do note that there are properties that are not inheritable.

Duplicate styles

If there are 2 competing styles, that is, with the same selectors and the same properties, it is the last property that is read that gets precedence. The page gets read from top to bottom.
For example…

p { color: yellow; text-decoration: underline; }
p { color: blue;  }

The color value will be blue because blue was the last one read.
The style applied will actually be…

p { color: blue; text-decoration: underline; }

The not so Basics

There is a more advanced way of determining style precedence, which is by way of a calculation called Specificity.
Quite simply, the more specific the selectors, the more precedence the style has.

If styles aren’t being applied the way you think they should be, it’s likely to be because of Specificity.

Here I am only talking about the precedence of the basic selectors, which should be all you need.
However, if you wan to know more, Specificity | HTML Dog is a good site to read.

Basic CSS Precedence

The basic precedence of selectors go in this order

  • In-line Style
  • Id tag
  • Class
  • Element

That is, inline styles are applied with the most precedence and HTML elements with the least.
Here is an example…

<html>
     <head>          
           <style type="text/css">
                body {
                     text-align:center;
                     color: white;
                }
                
                div {
                     background-color: #e5e5e5;
                }
 
                .testClass {
                     background-color: #0088cc;
                }
 
                #testId {
                     background-color: #555555;
                }
           </style>
     </head>
     <body>
           <div>
                <p>Div Only</p>
           </div>
           <div>
                <p class="testClass">Class overrides div</p>
           </div>
           <div>
                <p class="testClass" id="testId">Id overrides class and div</p>
           </div>
           <div>
                <p class="testClass" id="testId" style="background-color: #005580">
                    Inline overrides all</p>
           </div>
     </body>
</html>

The output of that is…

The output from the example of CSS Precedence.

It is that simple really.

Leave a Reply

Your email address will not be published. Required fields are marked *