Nesting and grouping in CSS (original) (raw)
Last Updated : 9 May, 2026
CSS Nesting & Grouping are techniques used to write efficient and organized stylesheets. They help reduce code repetition and improve readability and performance.
- Nesting allows writing styles inside parent selectors for better structure (mainly in preprocessors or modern CSS).
- Grouping lets you apply the same styles to multiple selectors using commas.
- Reduces redundancy, making code cleaner and easier to maintain.
Understanding Nesting in CSS
Nesting in CSS allows you to nest one style rule inside another. The child rule's selector is relative to the parent rule's selector. This method enhances the modularity and maintainability of CSS stylesheets, making the code more readable.
**Syntax
class1_selector class2_selector id_selector {
property: value;
}
**Example
table tr th {
background-color: beige;
}
Approach
- Select the id/class selector & add a space to separate one from the other.
- Add the style properties for the elements.
**Note: Be specific with the order of nesting.
**Example: Nesting the tag inside the tag and
HTML `
<style>
p a {
color: green;
}
table tr th {
background-color: beige;
}
</style>
<p>
This is a
<a href="https://www.geeksforgeeks.org/community/">link</a>
within a paragraph element.
</p>
<table style="width: 100%">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Roy</td>
<td>50</td>
</tr>
<tr>
<td>Sebin</td>
<td>65</td>
</tr>
<tr>
<td>Nicol</td>
<td>26</td>
</tr>
</table>
`
**Output: We got tag as green color and
Understanding Grouping in CSS
Grouping allows you to apply common styling properties to multiple elements at once. This reduces the length of your code, makes it easier to read, and speeds up page load times.
selector1, selector2 {
property: value;
}
Example (Without Grouping)
Instead of writing this long code, specifying the same properties to different selectors:
h1 {
padding: 5px;
color: grey;
}
p {
padding: 5px;
color: grey;
}
We can group them and write like this & we need the comma(****,**) to group the various selectors.
h1, p {
padding: 5px;
color: grey;
}
Approach
- Add