Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Nesting Styles for Cleaner Code | CSS-Präprozessoren und Sass
CSS-Layout, Effekte und Sass

Nesting Styles for Cleaner Code

Swipe um das Menü anzuzeigen

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?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 7. Kapitel 5

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 7. Kapitel 5
some-alt