Dremendo Tag Line

CSS Grouping and Nesting Selectors

Grouping and Nesting Selectors

In this lesson, we will explore CSS grouping and nesting techniques to enhance your web development workflow.

Grouping Selectors

Grouping selectors allows you to apply the same styles to multiple elements without repeating the same properties for each selector.

Example
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>CSS Grouping Selectors Example</title>

    <!-- Internal CSS -->
    <style>
        /* apply font color red to h1, p and ol tag */
        h1, p, ol {
            color: red;
        }
    </style>
</head>

<body>
    <h1>This is a sample heading</h1>
    <p>This is a sample paragraph.</p>
    <ol>
        <li>Tiger</li>
        <li>Elephant</li>
        <li>Dolphin</li>
        <li>Whale</li>
    </ol>
</body>

</html>
video-poster

Nesting Selectors

Nesting selectors in CSS refers to the practice of selecting and styling elements that are contained within or are descendants of other elements. This allows you to apply styles to specific elements within a structured HTML document hierarchy without needing to create separate rules for each element.

Example
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>CSS Nesting Selectors Example</title>

    <!-- Internal CSS -->
    <style>
        /* selects all the paragraph tags present within class d1 */
        .d1 p {
        	color: green;
        	font-weight: bold;
        	font-size: 18px;
        }

        /* selects all the paragraph tags present within class d2 */
        .d2 p {
        	color: red;
        	font-weight: bold;
        	font-size: 15px;
        }
    </style>
</head>

<body>
    <div class="d1">
    	<p>This is a sample paragraph.</p>
    </div>
    <div class="d2">
    	<p>This is a sample paragraph.</p>
    	<p>This is a sample paragraph.</p>
    </div>
</body>

</html>