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
Selected Reading
Selects all elements and all elements with CSS
The CSS comma selector allows you to apply the same styles to multiple elements by separating them with commas. This is useful when you want different element types to share the same styling rules.
Syntax
selector1, selector2, selector3 {
property: value;
}
Example: Styling Multiple Elements
The following example applies the same color and background styling to both <div> and <p> elements −
<!DOCTYPE html>
<html>
<head>
<style>
div, p {
color: blue;
background-color: orange;
padding: 10px;
margin: 5px;
}
</style>
</head>
<body>
<h1>Demo Website</h1>
<h2>Fruits</h2>
<p>Fruits are good for health.</p>
<div>
<p>This is demo text.</p>
</div>
</body>
</html>
The h1 and h2 headings appear in default black text. The paragraph "Fruits are good for health." and the div containing "This is demo text." both display with blue text on an orange background with padding and margins applied.
Example: Styling Headers Together
You can also group multiple heading elements to create consistent typography −
<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, h3 {
color: #333;
font-family: Arial, sans-serif;
text-align: center;
border-bottom: 2px solid #ccc;
}
</style>
</head>
<body>
<h1>Main Title</h1>
<h2>Subtitle</h2>
<h3>Section Header</h3>
<p>Regular paragraph text remains unaffected.</p>
</body>
</html>
All three headings (h1, h2, h3) appear with dark gray color, Arial font, center alignment, and a bottom border. The paragraph text displays with default styling.
Conclusion
The comma selector is an efficient way to apply identical styles to multiple elements without repeating CSS rules. This reduces code duplication and makes maintenance easier.
Advertisements
