Explain Codes LogoExplain Codes Logo

How to specify the order of CSS classes?

html
responsive-design
css
specificity
Nikita BarsukovbyNikita Barsukov·Dec 6, 2024
TLDR

The HTML class order doesn't affect the cascade. The order in the CSS file and specificity calls the shots. The last rule wins, given equal specificity:

.red { color: red; /* 🟥 Like red alert from Star Trek */ } .blue { color: blue; /* 🟦 Kinda feels like blue Monday here */}
<div class="blue red"></div> <!-- Star Trek day, color is red --> <div class="red blue"></div> <!-- Still a Star Trek day! -->

Tame the wild style application with specificity and !important, or rearrange your CSS rules.

Understanding the hierarchy of CSS classes

When stylesheet order matters

If your project uses multiple stylesheets, their loading order impacts the styling. Place generic stylesheets first, and specific overrides last for the expected outcome.

Crafting compound classes

An elegant way to stop wrestling with a bunch of classes is to combine common styles into new classes. This in turn cuts down complexity:

.button { /* Basic button styles */ } .red-button { /* Red variant for buttons. */ } /** * Combined class for a unique effect */ .special-red-button { /* Fusion of .button and .red-button */ }

Specificity and its role in the cascade

Knowledge of the cascade and its rules (IDs, classes, and elements) is pivotal. A higher specificity trumps order:

#uniqueElement { color: green; /* 🍏 An apple a day... */} /* An ID is mightier than a class */

Leverage specificity to commandeer style applications in need.

Deep diving into advanced styling techniques and potential pitfalls

Reining in the styling chaos through attribute selectors

Attribute selectors can target classes ending or beginning with specific strings, giving you more control over the chaos:

[class$="-error"] { border: 2px solid red; /* Nothing says error like a red border */ }

With $=, you can style classes ending with "-error", irrelevant of the class order.

The modular CSS promise

Betting on modular CSS, you can avoid clashes by wrapping styles into self-contained units. This results in more predictable behavior and less hair-pulling sessions.

Caution against overuse of !important

The !important tag is an emergency parachute. Use it in dire situations only. Misuse can lead to a maintenance purgatory, as it distorts the natural flow of the cascade and specificity rules.

Taming media query overrides

When media query styles come into play, they can override previous rules at different viewport sizes. Hence, these should be well-structured to prevent unintended effects:

.blue { color: blue; } @media (max-width: 600px) { .blue { color: darkblue; /* Because normal blue is too mainstream */} }