Creating compound CSS classes
We can create compound selectors by omitting the space between the &
nesting selector and any compound class though. This is demonstrated in the following example:
<button class="btn blue">A blue button</button>
<button class="btn red">A red button</button>
.btn {
&.blue {
background-color: blue;
}
&.red {
background-color: red;
}
}
Targeting pseudo classes
Pseudo classes can be targeted using native CSS nesting just the same as we have been used to with SCSS:
.btn {
:hover,
:focus {
text-decoration: underline;
}
:visited {
color: purple;
}
}
Infinite nesting
Firstly, let me say I don't like this and I hope you don't either AND you really shouldn't do it... but... you can carry on nesting until the cows come home if you're the sort of psychopath that likes writing frontend code like this:
.parent {
.child {
& ul {
& li {
& a {
:not(:visited) {
:hover {
translate: 0 -3px;
}
}
}
}
}
}
}
Using the & as a suffix to target a parent
One of the coolest features of SCSS nesting that I was almost certain wouldn't make it in to the spec for native CSS nesting is the ability to suffix the &
character in order to create parent selector conditional rules. Let's create an example where we want to create some conditional colours for a particular element if the parent has a modifier class of some sort:
<div class="box">...</div>
<div class="box dark">...</div>
.box {
background-color: #eee;
& p {
color: #111;
.dark & {
color: #eee;
}
}
.dark& {
background-color: #111;
}
}
Notice that because the .dark
modifier is on the div element with a class of 'box' the &
is used as a suffix without a space when nested in the .box
class directly but when the .dark
modifier class is nested inside of the p
selector a space is required before the &
suffix in order for the browser to understand we're referring to the parent .box
and not a .dark
modifier on the p
selector itself.
Learn CSS they said. It will be fun they said!
Nested media queries
One thing I absolutely HATED was when I had to write media queries in native CSS. Media queries had to live at the root of the stylesheet because CSS nesting wasn't a thing and that meant that any conditional styling for a particular selector had to live in a completely separate block and this was easily the fastest way for a stylesheet to get out of hand. But now that we have native CSS nesting we can do it just like we do it in SCSS:
.card {
.heading {
font-size: 1.1rem;
@media (min-width: 780px) {
font-size: 1.3rem;
}
}
}