Angelo Dini, Switzerland. Head of Product at Divio, co-founder of devguard.

Red pill or blue pill?

A question I ask my CAS Frontend Engineering students: does the order of class names in an HTML attribute change which CSS rule wins? Short answer, it does not.

By 2 min read

Article
Article 031 of 77
Category
Teach
Code samples
CSS, HTML

Does class name ordering matter?

Adding class names to an HTML document is as natural as almost any other HTML attribute. However, I've often encountered that the ordering of the class names needs to be understood.

A blister pack taken apart: the foil backing, the blister sheet of capsules, and one capsule popped out in orange.
Fig. 031 A blister pack taken apart: the foil backing, the blister sheet of capsules, and one capsule popped out in orange.

One of the questions I ask my students during the CAS Frontend Engineering class revolves around the following example:

CSS
.red {
  color: red;
}

.blue {
  color: blue;
}
HTML
<div class="red blue">First example</div>
<div class="blue red">Second example</div>

Have a closer look at the code above. Which colour is applied?

  1. The first example is red, and the second blue.
  2. The first example is blue, and the second red.
  3. The first and second examples are both blue.
  4. The first and second examples are both red.

The answer follows below.

Understanding the order of CSS classes

The order of CSS classes in HTML does not matter. What matters is the order in which styles are defined in the stylesheet. When two rules set the same property and carry the same specificity, the one declared last in the stylesheet always wins.

This concept can be tricky when dealing with multiple files and cause issues where developers misuse !important from time to time. That is why naming conventions, such as BEM, are essential. Additional tools and frameworks make encapsulation easier these days, Tailwind being a good example.

As such, the answer to the example above is the first and second examples are both blue.

This is a concise post with an important concept to understand, as more and more developers use CSS-in-JS solutions and seem to get this little fact wrong. 🫣

‘Till next time!