CSS - Group Selectors



Group Selectors in CSS

CSS group selector applies the same style to multiple elements at a time. The names of elements can be separated by commas. Group selector keeps CSS concise and avoids redundancy.

Syntax

The syntax for the CSS group selector is as follows:

 #selector_1, .selector_2, selector_3 { /* property: value; */ color: #04af2f } 

CSS Group Selectors Example

In this example, we have used the same style on all three elements using group selectors.

 <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> <style> span, #para, .myClass { background-color: #04af2f; color: white; } </style> </head> <body> <p id="para">This is a paragraph element.</p> <div class="myClass">This is a div element.</div> <br> <span>This is a span element.</span> </body> </html> 

Group Selectors Example with Pseudo-classes

In this example, we have used pseudo classes with group selectors. CSS :active pseudo-class changes the text color of the link and button on clicking while CSS :hover pseudo-class changes the background-color of the div and p element.

 <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> <style> .link:active, #btn:active { color: #04af2f; } .myDiv:hover, #para:hover { background-color: #031926; color: white; } </style> </head> <body> <div class="myDiv"> Hover over me </div> <p id="para">This is a paragraph.</p> <a class="link" href="#">Click on this link.</a> <br><br> <button id="btn">Click me</button> </body> </html> 
Advertisements