Nesting and grouping in CSS

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 tag inside the tag.

HTML


<html>

<head>


    <style>
        p a {
            color: green;
        }

        table tr th {
            background-color: beige;
        }
    style>


head>

<body>

    <p>
        This is a
        <a href="https://www.geeksforgeeks.org/community/">linka>
        within a paragraph element.
    p>

    <table style="width: 100%">
        <tr>
            <th>Nameth>
            <th>Ageth>
        tr>
        <tr>
            <td>Roytd>
            <td>50td>
        tr>
        <tr>
            <td>Sebintd>
            <td>65td>
        tr>
        <tr>
            <td>Nicoltd>
            <td>26td>
        tr>
    table>
body>

html>


Output: We got tag as green color and of beige color using nesting.

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