🎁 Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

A CSS tricky situation – the order of the CSS class names in the HTML tags

Let's say we have the following set of rules in a CSS file:

.red {
    color: red;
}

.blue {
    color: blue;
}

.green {
    color: green;
}

And the following tags in our HTML:

<div class="red green blue"> First div.</div>
<div class="blue red green"> Second div.</div>
<div class="green blue red"> Third div.</div>

The question is: what color will we have for these divs? Stop for a few seconds and try to answer the question.

The correct answer: they’re all green.

The order of the class names in HTML tags has no importance on the styles. The lines class="red green blue", class="blue red green" or class="green blue red" are the same thing.

All 3 selectors have the same specificity (just a simple class selector). And given that .green comes later in the stylesheet, it will override the .red and .blue selectors.

Therefore all the divs will have the color green. Cascading wins again.

By the way, this can make a great CSS interview question πŸ™‚

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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