Red pill or blue pill?
30. November, 2022 • 2 min read • Teach
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 questions I ask my students during the CAS Frontend Engineering class revolves 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?
- The first example is red, and the second blue.
- The first example is blue, and the second red.
- The first and second examples are both blue.
- 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!