This website may use cookies. More info. That's Fine x
Welcome Login

Grouping selectors (specify multiple selectors for css styling)


Css

Selector comma:

To specify multiple selectors for css styling, you can separate them with commas.

This allows you to apply the same set of styles to multiple elements without repeating the style definitions for each selector.

Syntax:

selector1, selector2, selector3 {
    /* css properties */
    property: value;
    property2: value2;
}

 

Eg: an example where the same styles are applied to <h1>, <h2>, and <p> elements:

h1, h2, p {
    color: blue;
    font-family: Arial, sans-serif;
    margin-bottom: 10px;
}

 

Eg2:

When several selectors share the same declarations, they may be grouped together to save writing the same rule more than once.

Each selector must be separated by a comma.

h1, h2, h3, h4 { padding: 1em; }
.highlight p, .highlight ul { margin-left: .5em; }
#main p, #main ul { padding-top: 1em; }

 

 

 

Common mistakes:

1. Forgetting to write each selector in full, when grouping selectors:

Eg: if you are trying to target two elements within the same containing block, and with the same ID, following is wrong:

/* incorrect */
#maincontent p, ul { border-top: 1px solid #ddd; }

 

It should be:

/* correct */
#maincontent p, #maincontent ul { border-top: 1px solid #ddd; }

 

 

2. Do not end the grouping with a comma:

Certain browsers will ignore the rule entirely:

.highlight p, .highlight ul, { margin-left: .5em; }

Created on: Thursday, March 10, 2011 by Andrew Sin