Using Parent Selector with Nesting

Tutorial 2 of 5

1. Introduction

1.1 Tutorial Goal

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).

1.2 Learning Outcomes

By the end of this tutorial, you will be able to:

  • Understand the use of the parent selector (&) in SASS/SCSS.
  • Implement nesting with the parent selector (&).
  • Simplify your SASS/SCSS code by using the parent selector effectively.

1.3 Prerequisites

Before starting this tutorial, you should have a basic understanding of CSS and a working knowledge of SASS/SCSS.

2. Step-by-Step Guide

2.1 Parent Selector

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.

2.2 Nesting with Parent Selector

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.

3. Code Examples

3.1 Basic Usage of Parent Selector

.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;
}

3.2 Using Parent Selector with Pseudo-Classes

.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;
}

4. Summary

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.

5. Practice Exercises

5.1 Exercise 1

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;
}

5.2 Solution 1

.nav-item {
  &.active {
    color: red;
  }

  &.disabled {
    color: grey;
  }
}

5.3 Exercise 2

Given the following CSS, convert it to SASS/SCSS using the parent selector where appropriate:

.button::after {
  content: '';
}

.button:hover {
  background-color: yellow;
}

5.4 Solution 2

.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!