Red pill or blue pill?

30. November, 2022 2 min read Teaching

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.

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

.red {
  color: red;
}

.blue {
  color: blue;
}
<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 styles with the same attributes and names are declared, the one last on 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 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!