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;
    }
&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p id="para"&gt;This is a paragraph element.&lt;/p&gt;&lt;div class="myClass"&gt;This is a div element.&lt;/div&gt;&lt;br&gt;&lt;span&gt;This is a span element.&lt;/span&gt;&lt;/body&gt;&lt;/html&gt;</pre>

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;
    }
&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="myDiv"&gt;
    Hover over me
&lt;/div&gt;&lt;p id="para"&gt;This is a paragraph.&lt;/p&gt;&lt;a class="link" href="#"&gt;Click on this link.&lt;/a&gt;&lt;br&gt;&lt;br&gt;&lt;button id="btn"&gt;Click me&lt;/button&gt;&lt;/body&gt;&lt;/html&gt;</pre>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *