CSS Grouping Selectors


In CSS, a Grouping Selector enables you to select more than one element and assign the same styles to those elements without repeating the rules.

  • It saves time and reduces repetition in code.
  • Selectors are separated by commas (,).

Syntax

selector1, selector2, selector3 {
  property: value;
} 
  • The style inside the curly braces {} applies to all selectors listed.

css-grouping-selectors


Example

<!DOCTYPE html>
<html>
<head>
  <style>
    h1, h2, h3 {
      color: darkred;
      text-align: center;
    }

    p, li {
      font-size: 18px;
      color: #555;
    }
  </style>
</head>
<body>

<h1>Main Heading</h1>
<h2>Subheading</h2>
<h3>Section Title</h3>

<p>This paragraph shares styles with list items.</p>

<ul>
  <li>List item one</li>
  <li>List item two</li>
</ul>

</body>
</html> 

Advantages

  • Reduces repetition in stylesheet.
  • Helps keep the code cleaner, shorter and easier to maintain.
  • Very handy when you have multiple elements with same styles.

Grouping Different Types of Selectors

Element selectors

p, h1 {
  color: blue;
} 

Class selectors

.box, .container {
  border: 1px solid #ccc;
}

ID selectors

#main, #footer {
  background-color: #f9f9f9;
}

Mix of selectors

h1, .title, #header {
  text-align: center;
  color: teal;
}



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.