The parent selector is nothing but an ampersand symbol (&).
The parent selector (&) is used to refer to the outer selector when you nest selectors.
I love it! It makes it so much easier to reuse the outer selector and helps to create more complex styles by following a simple syntax.
For e.g. take a look at this SCSS:
.alert {
&:hover {
font-weight: bold;
}
&.second-class{
font-size: 20px;
}
}
Here’s the compiled CSS:
.alert:hover {
font-weight: bold;
}
.alert.second-class {
font-size: 20px;
}
Those are just two different elements/selectors style but can you imagine doing that for tons of nested elements?!
You can refer to the outer selector after as well. Like this:
.alert {
:not(&) {
opacity: 0.8;
}
}
Here’s the compiled CSS:
:not(.alert) {
opacity: 0.8;
}
If you don’t leave a space or add a bracket, you might experience weird behavior.
Here’s the GitHub issue page related to that.
Add Suffixes
Use the parent selector, you can add additional suffixes to the outer selector, as long as the outer selector ends with an alphanumeric name.
Like this:
.accordion {
max-width: 600px;
margin: 4rem auto;
width: 90%;
font-family: "Raleway", sans-serif;
background: #f4f4f4;
&__copy {
display: none;
padding: 1rem 1.5rem 2rem 1.5rem;
color: gray;
line-height: 1.6;
font-size: 14px;
font-weight: 500;
&--open {
display: block;
}
}
}
Compiled CSS will be this:
.accordion {
max-width: 600px;
margin: 4rem auto;
width: 90%;
font-family: "Raleway", sans-serif;
background: #f4f4f4;
}
.accordion__copy {
display: none;
padding: 1rem 1.5rem 2rem 1.5rem;
color: gray;
line-height: 1.6;
font-size: 14px;
font-weight: 500;
}
.accordion__copy--open {
display: block;
}
css selectors examples nested parent selector sass