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.
nav a
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 <nav> parent.
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.
nav a.button
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.