I’ve been writing CSS for a long time but I recently discovered that browsers read selectors from right to left rather than the intuitive left to right. I previously thought I was “scoping” my styles by doing something like this.
I thought browsers would hone in on the
<nav> element then find all the child
<a> tags. But it turns out browsers start by looking at all the
<a> tags then check to see if they have a
This misunderstanding has performance implications if you have a large document and a ton of poorly written selectors. Luckily, I haven’t really noticed any ill effects in the wild since modern browsers are pretty damn amazing.
But now that I know this, I’ll at be a little more thoughtful in my selectors and consider adding a class to the last element. It could look something like this.
I do think this has the potential to make HTML less readable if you’re throwing in redundant classes just to optimize selectors. Things like
<a class="link" /> just seems absurd to me. Maybe it’s better to not have classes on the last element in a lot of cases…I’m torn. But this does give me a new appreciation for things like BEM even though I find the syntax to be so noisy.