English translation of a Persian article from the WebTarget archive. The date above is the original publication date. Some advice, especially technical details, may be outdated.

Grouping selectors

Several elements in a stylesheet often share the same styles. Repeating those declarations increases the size of the CSS file and makes it harder to manage and edit.

Grouping selectors lets you define shared styles once. It reduces repetition and gives you a clearer place to control the elements that use those styles.

CSS

h1 {
    Color:#cccccc;
}
h2{
    Color:#cccccc;
}
p{
    Color:#cccccc;
}

Separate the selectors with commas and place their shared declarations in a single rule. In the following example, h1, h2, and p all receive the same colour.

CSS

h1,h2,p {
    Color:#cccccc;
}

HTML

<h1>Hello World!</h1>
<h2>Smaller heading!</h2>
<p>This is a paragraph.</p>

Selecting elements inside other elements

A descendant selector lets you select an element inside a particular container. In the next example, every paragraph receives a green text colour and centred alignment. The .marked class gives its container a green background, while .marked p changes the paragraphs inside it to white. Those paragraphs still match the general p rule, so their text remains centred. Terminology note: this is descendant selection, rather than the modern CSS nesting syntax.

CSS

p {
    Color:green;
    Text-align:center;

}

.marked {
    Background-color:green;
}

.marked p {
    Color:white;
}

HTML

<p>This is a green, center-aligned paragraph.</p>
<div class="marked">
    <p>This paragraph is white on a green background.</p>
</div>
<p
>p elements inside a "marked" classed element keeps the alignment style, but has a different
text color.</p
>

The same technique works when selecting a span inside a paragraph. Here the paragraph is green, while its span is red.

CSS

p {
    Color:green;
}
p span {
    color:red;
}

HTML

<p> this is a <span> example </span> text </p>