DEV Community

Cover image for Stop Repeating CSS! Learn CSS Nesting
Shefali
Shefali

Posted on • Originally published at shefali.dev

Stop Repeating CSS! Learn CSS Nesting

CSS Nesting lets you write CSS rules inside other CSS rules. This makes your code cleaner, shorter, and easier to understand.

Think of it like how HTML elements are placed inside each other. For example, a <ul> inside a <nav>.

CSS Nesting works the same way, so you write styles for child elements inside the parent’s styles.

Why use CSS Nesting?

  • Keeps your CSS organized: You group styles that belong together.
  • Makes your code easier to read: You can see the relationship between elements clearly.
  • Saves time: You write less repeating code.

How CSS Nesting Works

Here’s a quick example:

nav {
  background: #333;
  ul {
    list-style: none;
    li {
      color: white;
      padding: 10px;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Here,

  • The <nav> element has a dark background (#333).
  • Inside <nav>, all <ul> lists will have no bullet points (list-style: none).
  • Inside those <ul> lists, every <li> (list item) will have white text and 10 pixels of padding.

Because the styles for ul and li are written inside the nav block, these styles only apply to ul and li elements inside the nav. This makes sure your CSS affects exactly the parts of your page you want, without extra code.

Browser Support

Good news! CSS Nesting now works in all major browsers:

  • Chrome: from v112 (April 2023)
  • Edge: from v112 (April 2023)
  • Safari: from v16.5 (May 2023)
  • Firefox: from v117 (August 2023)
  • Opera + Mobile browsers: fully supported too

So yes, it’s safe to use CSS Nesting in your projects today without worrying about compatibility.

Check browser support for CSS nesting!

Final Thoughts

CSS Nesting is such a handy feature. It:

  • Keeps your CSS clean and organized
  • Saves you from writing the same code again and again
  • Matches the way your HTML is structured

Give it a try in your next project and let me know how it goes for you in the comments!👇🏻


That’s all for today!

For paid collaboration, connect with me at: connect@shefali.dev

If you enjoy my work and want to support what I do:

👉 Become a Patreon supporter
👉 Or buy me a coffee

Every small gesture keeps me going! 💛

Top comments (0)