TOC

The community is working on translating this tutorial into Russian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Selectors:

Grouping selectors

So far, all of our selectors have only targeted one class, one ID or one element. However, CSS makes it ridiculously easy to target more than one element at the same time, allowing you to specify the same properties and rules for more than one element at the same time - just separate the selector names with a comma and you're good to go. This is another one of those features of CSS which allows for greater code re-usability - there's no reason to specify the same properties for several elements/classes, if you can re-use them. Here's a nifty example:

<style type="text/css">
h1, h2, h3 {
	color: Maroon;
}
</style>

<h1>Main header</h1>

<h2>Header level 2</h2>

<h3>Header level 3</h3>

As you can see, we can now target h1, h2 and h3 elements with one, single rule, instead of having to specify it for each of them. You can mix and match with class and ID selectors too, if you want to:

h1#main, h2.sub, h3, .someClass, #anID {
	color: Maroon;
}

Now the really cool thing is that thanks to CSS and its cascading nature, you can still add rules specific to one or several of elements and the browser will apply it according to precedence (we'll talk more about that later). Check out this example:

<style type="text/css">
h1, h2, h3 {
	color: Maroon;
	text-align: center;
}

h1 {
	background-color: Silver;
	padding: 10px;
	text-align: left;
}

h2, h3 {
	background-color: Gray;
	padding: 5px;
}
</style>

<h1>Main header</h1>

<h2>Header level 2</h2>

<h3>Header level 3</h3>

Try out the example and notice how the browser uses the appropriate properties from the selectors. We are able to group together the common properties in one selector, and then we can add and even modify them in the more specific selectors later on.

Summary

Grouping selectors together makes it so easy to re-use CSS code, while maintaining a very high degree of flexibility - if a common rule is used in several places, you can still overrule it by writing a more specific selector.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!