In this tutorial, we aim to give you a detailed understanding of the parent selector (&) in SASS/SCSS and how to effectively use it with nesting. The parent selector can be a powerful tool in your SASS/SCSS workflow, as it can simplify your code and make it more DRY (Don't Repeat Yourself).
By the end of this tutorial, you will be able to:
Before starting this tutorial, you should have a basic understanding of CSS and a working knowledge of SASS/SCSS.
The parent selector (&) in SASS/SCSS is used to reference the parent selector of a nested rule. It can be very useful for pseudo-classes, pseudo-elements, and modifier classes.
In SASS/SCSS, you can nest your CSS rules inside one another. This nesting can be combined with the parent selector (&) for more complex and dynamic styles.
.btn {
&--primary {
background-color: blue;
}
&--danger {
background-color: red;
}
}
In this example, the & symbol represents the parent selector (.btn). The output CSS will be:
.btn--primary {
background-color: blue;
}
.btn--danger {
background-color: red;
}
.link {
&::before {
content: "";
}
&:hover {
color: orange;
}
}
In this example, the & symbol represents the parent selector (.link). The output CSS will be:
.link::before {
content: "";
}
.link:hover {
color: orange;
}
In this tutorial, we've gone over the parent selector (&) and how you can combine it with nesting in SASS/SCSS. You've learned how to use the & symbol to refer to the parent selector, and we've seen how this can simplify your code, making it more DRY.
Given the following CSS, convert it to SASS/SCSS using the parent selector where appropriate:
.nav-item.active {
color: red;
}
.nav-item.disabled {
color: grey;
}
.nav-item {
&.active {
color: red;
}
&.disabled {
color: grey;
}
}
Given the following CSS, convert it to SASS/SCSS using the parent selector where appropriate:
.button::after {
content: '';
}
.button:hover {
background-color: yellow;
}
.button {
&::after {
content: '';
}
&:hover {
background-color: yellow;
}
}
Keep practicing with the parent selector and nesting. Try it out on your projects and see how it can simplify your SASS/SCSS code!