Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Nesting Styles for Cleaner Code | Préprocesseurs CSS et Sass
Mise en page CSS, Effets et Sass

Nesting Styles for Cleaner Code

Glissez pour afficher le menu

The next powerful feature is nesting. It allows us to nest one selector within another to create more organized and readable code. We can group styles and reduce the code we need to write.

Let's imagine that we need to create the website navigation.

navigation example

The html for this navigation will look the following:

<nav>
  <ul>
    <li>
      <a href="#home">Home</a>
    </li>
    <li>
      <a href="#about">About</a>
    </li>
    <li>
      <a href="#price">Price</a>
    </li>
  </ul>
</nav>

Considering that besides the navigation, we use the same html tags (ul, li, a) multiple times throughout the project. To add some styles exactly to these elements, we need to use nesting rules in css. So, css can look as follows:

nav {
  background-color: rebeccapurple;
  border-radius: 10px;
  padding: 10px;
}

nav ul {
  list-style: none;
  padding-left: 0;
}

nav ul li {
  display: inline-block;
  margin: 0 10px;
}

nav ul li a {
  text-decoration: none;
  color: aquamarine;
}

nav ul li a:hover {
  text-decoration: underline wavy;
}

Now, let's see how sass can makes our lives easier. We will group all these styles in one block. The code is rewritten into:

nav {
  background-color: rebeccapurple;
  border-radius: 10px;
  padding: 10px;

  ul {
    list-style: none;
    padding-left: 0;

    li {
      display: inline-block;
      margin: 0 10px;

      a {
        text-decoration: none;
        color: aquamarine;
        
        &:hover {
          text-decoration: underline wavy;
        }
      }
    }
  }
}

It's like we're nesting the child's style block in its parent block. Pay attention that the & symbol in the &:hover selector is used to reference the parent selector, in this case, a. This is a shorthand way of writing a:hover and makes it easier to write nested selectors without repeating the parent selector multiple times.

question mark

What is the benefit of using sass nesting?

Sélectionnez la réponse correcte

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 7. Chapitre 5

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 7. Chapitre 5
some-alt