A couple more words on CSS nesting
So nesting has landed in Safari Technology Preview—well done to the WebKit team and hallelujah!
Except CSS nesting feels like a distinctly 2010s approach to writing styles. I've written a little bit about how I feel about CSS nesting before, but I've got a couple more objections:
It unnecessarily couples components. Consider this (hopefully) representative example:
.card {
box-shadow: 0px 2px 4px rgba(0,0,0,0.15);
padding: 1rem;
& .image {
display: block;
margin: -1rem;
}
& .content {
margin-top: 1rem;
}
}
Why is the style of .image
and .content
coupled to .card
? The .card
element should be responsible for the display of its children; an .image
shouldn’t care about the context in which it’s displayed. This won’t be the only usage of .image
in your stylesheet. Skip the nesting here and keep all of your .image
styles co-located and context-agnostic.
.card { box-shadow: 0 2px 4px rgba(0,0,0,0.15); }
.image { display: block; }
.content { padding: 1rem; }
If you do need context-dependent styles, then you’re probably already using something like BEM. Speaking of which: nesting makes it difficult to search for styles in your codebase, especially if you’re using a methodology like BEM.
.card {
&__image {}
&__content {}
}
Developers looking for .card__image
won’t find what they’re looking for. Prefer instead:
.card {}
.card__image {}
That’s not to say that I’m not going to use nesting. Of course I’m going to use it: more tools in the toolbelt is always nice. But better approaches to tools, and more _selective use of tools, is always going to trump the brute force of numbers.
Further reading
Next
Adding search to my website was a fun project for the weekend, and has made my own website like 40% more useful to me.