A new weapon has arrived in our zombie-smacking CSS arsenal: Nested selectors. (True, it’s been available with SASS and other pre processors for a long time, but it’s now available natively in all modern browsers.) Instead of writing:
.zombie {
font-size: 1.2em;
}
.zombie h3 {
font-size: 1.5em;
}Code language: CSS (css)You can now write
.zombie {
font-size: 1.2em;
h3 {
font-size: 1.5em;
}
}While not saving much space, it more importantly shows a clear relationship between the h3 and the .zombie and forces modularity. These rules have to be next to each other rather than scattered through the document. The resulting code is more readable and easier to understand for any developer that comes after you.
Previous versions of the specification required you use an & before the nested selector, e.g.
.zombie {
font-size: 1.2em;
& h3 {
font-size: 1.5em;
}
}
And you can still use that if you find it clearer or it helps you read the selectors, but it’s not required unless you’re trying to write a compound selector. For example, you could take this situation
.undead {
color: red;
}
.undead.crawler {
color: blue
}Code language: CSS (css)And nest it like
.undead {
color: red;
&.crawler {
color: blue
}
}
If you didn’t use the &, the browser would have parsed it as .undead .crawler, i.e. looking for this HTML:
<div class=“undead”>
<div class=“crawler”></div>
</div>Code language: HTML, XML (xml)Instead of parsing it as .undead.crawler, i.e. looking for this HTML:
<div class=“undead crawler”></div>Code language: HTML, XML (xml)