Efficient CSS Styling with Grouping Selectors


Grouping Selector

Grouping Selectors in CSS allow you to apply the same styles to multiple selectors without repeating the style declarations. This is useful for keeping your CSS code concise and more maintainable when you want to apply the same styles to multiple elements or selectors.

Syntax: To group selectors together in CSS, you simply separate them with commas (,). The styles enclosed within the curly braces {} will be applied to all the selectors listed in the group.

selector1, selector2, selector3 {
  /* Common styles go here */
}

Source Code :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Grouping Selector</title>
    <style>
      h1,
      h2,
      p {
        color: red;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <h1>Grouping Selector</h1>
    <p>
      HTML elements or tags represent different parts of a web page's structure and content, such as <b> headings, paragraphs</b>, lists, images, links, and more. XML tags serve a similar purpose but can be customized to define the structure of data within an XML document according to a specific
      schema.
    </p>
    <h2>Sub Heading</h2>
    <ul>
      <li>HTML</li>
      <li>CSS</li>
      <li>JavaScript</li>
    </ul>
  </body>
</html>

Live Preview

Grouping Selectors: This CSS code groups three selectors together: h1, h2, and p. They are separated by commas (,). This grouping allows you to apply the same styles to all three types of HTML elements in a concise manner, rather than writing separate style declarations for each element.

Common Styles:color: red;: This rule sets the text color of the selected elements to red. Therefore, all <h1>, <h2>, and <p> elements that match these selectors will have red text.

In summary, this CSS code selects and applies the same styles (red text color and centered text alignment) to all <h1>, <h2>, and <p> elements on the web page. This grouping approach helps maintain code efficiency and consistency when you want to apply shared styles to multiple elements without duplicating style declarations for each selector individually.


CSS Tutorial


Properties Reference


Cascading Style Sheet


Flexbox Tutorial


CSS Grid Tutorial


Transitions Properties


CSS Properties with Examples


CSS Selectors


CSS Pseudo Elements


CSS Attribute Selectors


Input Pseudo Classes


CSS Examples


CSS Animation Projects