Zwei Menschen kollaborieren am Whiteboard
Tim, Kiya | 08.02.2024

Understanding CSS Nesting in Detail

Web > Understanding CSS Nesting in Detail

What is CSS Nesting? CSS Nesting allows us to write CSS rules within other rules. This makes our code clearer and easier to maintain. This feature, which was previously only available through preprocessors like SASS or LESS, is now part of the official CSS specification. This means that we can now carry out a deeper and more intuitive nesting of CSS rules directly in our stylesheets.

Example:

Without nesting:

1.navbar {
2/* Style for the navigation bar */
3}
4
5.navbar .navbar-link {
6/* Style for links in the navigation bar */
7}
8
9.navbar .navbar-link:hover {
10/* Style for links on hover */
11}

With Nesting:

1.navbar {
2/* Style for the navigation bar */
3  
4  > .navbar-link {
5  /* Style for links */
6    
7    &:hover {
8    /* Style for links on hover */
9    }
10  }
11}

Why is this cool?

  • Clarity: Everything that belongs to an element stays together.

  • Maintainability: Changes are easier, as the structure is clearer.

  • Less writing: Less repetition of selectors.

Notes:

  • Browser support varies. Check the compatibility for your projects.

  • Use this function with care. Too deep nesting can also become unclear.

Further readings:

Content
  • What is CSS Nesting?
  • How to use CSS Nesting?
  • Why is CSS Nesting cool?
  • What needs to be observed while using CSS Nesting?
  • Additional resources on CSS Nesting
Tim Tilch
Tim (Softwareentwickler)

Als erfahrener Geodaten-Spezialist habe ich eine Leidenschaft für die Entwicklung und Visualisierung von Karten- und Geoinformationssystemen. Meine Expertise ermöglicht es mir, komplexe Geodaten verst... mehr anzeigen

GitlabGithub
Kiya

... ist unsere engagierte und leidenschaftliche Künstliche Intelligenz und Expertin für Softwareentwicklung. Mit einem unermüdlichen Interesse für technologische Innovationen bringt sie Enthusiasmus u... mehr anzeigen

Standort Hannover

newcubator GmbH
Bödekerstraße 22
30161 Hannover

Standort Dortmund

newcubator GmbH
Westenhellweg 85-89
44137 Dortmund