Hacker News new | ask | show | jobs
by dncornholio 1540 days ago
Which rules wins is the rule that is the most specific. This article explains it as having 'the most hits'. Whatever that means.
1 comments

Not just most specific, though. IDs are weighted higher than classes, so if there's a tie between 2 rules, an ID wins over a class, even if it comes first. If 2 classes (or things weighted the same as classes) tie, the later rule wins.

https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

Class specificity can be artificially increased to work around this.

    .foo.foo { color: blue; }
    .bar { color: red; }

    <div class=”foo bar”>
      I’m blue
    </div>
shouldn't that be foo.bar?
No, the idea is that .foo.foo increases the specificity of .foo over .bar
Ok, and checking it I can see that foo.foo.foo increases specificity yet again and so on infinitum I suppose.

I suppose this behavior is specified somewhere and you've read that part of the spec thus explaining how you know it, however as the class declaration is not 'foo foo bar' I think if I were to read it I would conclude that I disagreed with whatever logic was given.

In fact this really seems to take away part of the argument for important, why not just make your rule be foo.foo.foo.foo.foo.foo when you really want to override something. Add enough foos you're sure to win out.

on edit: why I would find foo.foo acceptable if the class declaration was 'foo foo bar' is because, while I find 'foo foo bar' silly I can see why someone would specify what happens when it occurs. I would also have accepted if the spec said 'foo foo bar' is reduced down to 'foo bar' and foo.foo does not make any sense. I guess I find foo.foo not making sense as being my preferred behavior.

Here’s the thing: while the doubled-class ”.foo.foo” trick increases specifity over a single class, it doesn’t completely override selector specificity like !important does: you can still override anything set by ”.foo.foo” with a more specific selector like ”div.foo” or even ”.quux .foo” without having to use the duplicate classname everywhere.
I have to also say with the introduction of variables this starts to look crazy

:root { --main-color: brown; } .foo.bar { --main-color: red; } .foo.foo { --main-color: blue; } .bar { --main-color: red; color: var(--main-color); }

anyone actually use this foo.foo method of increasing specificity? Because I think difficult to debug.

It is useful when writing multi-theme, multi-color-palette design systems, for example to override colors in a specific component on a specific part of the site but only in a specific theme.