The Order of CSS Classes in HTML Doesn’t Matter

Avatar of Robin Rendle
Robin Rendle on

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

That’s right! And I can prove it, too. Let’s look at some CSS first:

.a {
  color: red;

.b {
  color: blue;

And now let’s look at some markup:

<div class="a b">Here’s some text</div>

The text is going to be blue because .b is defined last in the CSS, right? But what if we go about and switch the order in which those classes are called in HTML:

<div class="b a">Here’s some text</div>

What color do you think the text should be? Red or blue?

This certainly might sound like a silly question but it tends to trip up a lot of folks who happen to be familiar with CSS-in-JS solutions. And this week I’ve spoken to two very senior front end engineers who thought similarly as well!

But the text in the example above will always be blue no matter what order those CSS classes are in. And that’s because the markup is just reading the CSS in the order that it’s written — the cascade wins in this example.