Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Grouping Selectors in CSS
CSS grouping selectors allow you to apply the same styles to multiple elements at once by separating selectors with commas. This technique reduces code repetition and makes your CSS more maintainable and efficient.
Syntax
selector1, selector2, selector3 {
property: value;
}
How Grouping Selectors Work
When you separate selectors with commas, the CSS rules apply to all the specified elements. You can group any type of selectors including element selectors, class selectors, ID selectors, and attribute selectors.
Example 1: Grouping Element Selectors
The following example applies the same background and text styles to both div and article elements −
<!DOCTYPE html>
<html>
<head>
<style>
div, article {
background-color: #04af2f;
color: white;
text-align: center;
padding: 20px;
margin: 10px 0;
font-size: 18px;
}
</style>
</head>
<body>
<h2>Grouping Element Selectors</h2>
<div>This is a div element</div>
<article>This is an article element</article>
</body>
</html>
Both the div and article elements display with green background, white text, center alignment, and consistent spacing.
Example 2: Grouping ID Selectors
You can also group ID selectors to apply common styles −
<!DOCTYPE html>
<html>
<head>
<style>
#header, #footer {
background-color: #333;
color: white;
padding: 15px;
text-align: center;
border: 2px solid #555;
}
</style>
</head>
<body>
<div id="header">Website Header</div>
<p>Main content area</p>
<div id="footer">Website Footer</div>
</body>
</html>
Both header and footer sections display with dark gray background, white text, padding, and borders using the same grouped styles.
Example 3: Mixed Selector Types
You can group different types of selectors together −
<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, .highlight, #important {
color: #e74c3c;
font-weight: bold;
border-left: 4px solid #e74c3c;
padding-left: 10px;
}
</style>
</head>
<body>
<h1>Main Heading</h1>
<h2>Sub Heading</h2>
<p class="highlight">Highlighted paragraph</p>
<div id="important">Important notice</div>
</body>
</html>
All elements display with red text, bold font, and a red left border, demonstrating how different selector types can be grouped together.
Conclusion
Grouping selectors in CSS is an essential technique that helps reduce code duplication and maintain consistency across your stylesheets. By using commas to separate selectors, you can efficiently apply the same styles to multiple elements regardless of their selector type.
