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; } } }
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.
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!
If you’re new to web development, check out Learnify — my curated platform with beginner-friendly tutorials to help you learn web development step-by-step with examples and simple explanations.
If you enjoy my work and want to support what I do:
👉 Become a Patreon supporter
👉 Or buy me a coffeeEvery small gesture keeps me going! 💛
Follow me on X (Twitter) to get daily web development tips & insights.
Enjoyed reading? You may also find these articles helpful.
Stop Struggling with CSS: Master Inheritance, Specificity & Cascade Now
What is !important in CSS and Why You Shouldn’t Use It