6 ms·
I’ve noticed many CSS authors don’t seem to know that you can just repeat a selector to increase its specificity. For your example, `.className.className` incre
by csnover 5y ago
I’ve noticed many CSS authors don’t seem to know that you can just repeat a selector to increase its specificity. For your example, `.className.className` increases the specificity without adding more reliance on DOM structure.
- jimhi 5y agoI did not know this, thanks for the tip
- jaywalk 5y agoWow, I've been doing CSS for a very long time, and had no idea about repeating the selector to increase specificity. That'll come in very handy, thank you!
- dopamean 5y agoThis is a really cool tip.
- 3np 5y agoEDIT: Memory was playing tricks on me
- HWR_14 5y agoVery cool tip. Do you know if that's an implementation artifact or part of the spec?
- csnover 5y agoIt is part of the spec, and is explicitly noted to avoid confusion starting in Selectors Level 3[0]: > Note: Repeated occurrences of the same simple selector are allowed and do increase specificity. [0] https://www.w3.org/TR/selectors-3/#specificity https://www.w3.org/TR/selectors-3/#specificity
- HWR_14 5y agoThanks!
- afiori 5y agoyou can also override id selectors with :is *:is(#a#b, .someclass) {...} overrides any selector with a single id; you add more ids to override more specific selectors (except inline stiles and !important)
- lrenn 5y agoMind blown. How the hell did I not know this.
- mort96 5y agoBut that only works if you only need to increase "class-level" specificity. If you're trying to overwrite a style set with IDs, you're gonna need to either use IDs yourself or use !important. Sometimes you may not want to use IDs.
- csnover 5y agoRight—you can do the same thing with ID selectors, they just always have a higher specificity because they are in bucket A[0], whereas virtually all the other selectors are in bucket B. If you really have to select that element by ID for some reason, you can use an attribute selector instead—`[id=foo]`—and then it’s also in bucket B and can be controlled in the normal way. Basically, you should consider ID selectors (and element selectors) an antipattern and never use them. [0] https://www.w3.org/TR/selectors-4/#specificity-rules https://www.w3.org/TR/selectors-4/#specificity-rules