I recently took a course at Frontend Masters, and one thing that stuck with me is how important it is to understand CSS specificity. Its also wild how many problems !important
can cause.
So here’s the breakdowwn: specificity decides which CSS rule gets applied when multiple rules target the same element. Think of it like a pecking order—some rules just have more weight than others.
Here’s how it breaks down:
- Inline styles (like
style="color: red;"
) - IDs (like
#my-id
) come next. - Classes (like
.my-class
), attributes, and pseudo-classes are right behind. - Elements (like
div
,h1
) have the least weight.
Now, enter !important
. It feels like it fixes everything, but trust me, it sucks. Sure, it overrides everything, but it creates chaos. You’ll find yourself chasing down every !important
rule just to figure out why things are going haywire.
Instead of leaning on !important
, focus on writing clear, specific selectors. CSS has a cascade for a reason, and working with it will save you from future headaches. In fact, I also heard the developers at CSS initially added it specify style sets for government websites and websites that require legally same styles across pages, and they later regretted it…
Your future self will thank you when your CSS is more manageable. Thanks to that Frontend Masters course, I’m definitely more cautious about this now…thanks for reading.