Grouping Selectors in CSS



CSS grouping selector is used to select multiple elements and style them together. This reduces the code and extra effort to declare common styles for each element. To group selectors, each selector is separated by a space.

In this article, we will be understanding how to apply grouping selectors in CSS.

Applying Grouping Selectors in CSS

We have applied grouping selector using element name and using id of the element.

  • We have used div and article element as grouping selector to apply background-color, color and text-align properties to div and article tag making it center aligned with green background and white text-color.
  • We have also used id1 and id2 id selectors as group selectors to apply padding and border to h4 and span element.

Example

Here is the complete example code implementing above mentioned steps to apply grouping selectors.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Grouping Selector in CSS</title>
    <style>
        div, article {
            background-color: #04af2f;
            color: white;
            text-align: center;
            font-size: 20px;
        }
        #id1, #id2 {
            padding: 5px;
            border: 2px solid black;
        }
    </style>
</head>
<body>
    <h2>
        Grouping Selector in CSS
    </h2>
    <p><strong>
            In this example, both div and article
            element have same background-color, text
            color and aligned to center using
            grouping selector.
        </strong></p>
    <div>
        This is a div element
    </div>
    <br>
    <article>
        This is an article element.
    </article>
    <p><strong>
            In this example, both h4 and span
            element have same padding, and
            border properties using grouping
            selector.
        </strong></p>
    <h4 id="id1">
        This h4 element has padding and border
        properties.
    </h4>
    <span id="id2">
        This span element also has padding and
        border properties.
    </span>
</body>
</html>

You can refer to our CSS-Selectors tutorial for more info.

Conclusion

In this article, we have understood applying grouping selectors in CSS is a simple task. We have used elements and id to apply group selectors and design the structure of HTML.

Updated on: 2024-08-14T12:19:51+05:30

19K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements