Written by Harry Roberts on CSS Wizardry.
Table of Contents
- It’s all about the key selector…
- Real-life example
- Exceptions
- Final word
One type of CSS in particular makes me cringe every time I see it; poor selector intent. Poor selector intent means carpet bombed selectors whose key selector has way too broad a reach; a selector like .header ul{}
as opposed to one like .main-nav{}
; .widget h2{}
instead of .widget-title
; article > p:first-child{}
as opposed to .intro{}
. Selectors whose intent isn’t specific enough.
It’s worth noting that selector intent is something I completely made up at some point today; if you think there’s a better name then please let me know!
Let’s take a closer look at the .header ul{}
example. Let’s imagine that ul
is indeed the main navigation for our website. It lives in the header, as you might expect, and is currently the only ul
in there; .header ul{}
is fine, right? Not really. I mean sure, it might work, but it’s not very good. It’s not very future proof and certainly not explicit enough. As soon as we add another ul
to that header it will adopt the styling of our main nav and the the chances are we won’t want it to. This means we either have to refactor a lot of code or undo a lot of styling on subsequent ul
s in that .header
to remove the effects of the far reaching selector.
Your selector’s intent must match that of your reason for styling something; ask yourself ‘am I selecting this because it’s a ul
inside of .header
or because it is my site’s main nav?’. The answer to this question will determine your selector.
It’s all about the key selector…
What determine
Leave a Reply