CSS Grouping and Nesting Selectors

Grouping Selectors

In style sheets there are often elements with the same style.
h1
{
color:green;
}
h2
{
color:green;
}
p
{
color:green;
}
To minimize the code, you can group selectors.
Separate each selector with a comma.
In the example below we have grouped the selectors from the code above:

Example

<html>
<head>
<style type="text/css">
h1,h2,p
{
color:green;
}
</style>
</head>

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

Try it yourself in Notepad or Dreamweaver by coping and pasting the code above.
Result:

Hello World!

Smaller heading!

This is a paragraph.

Nesting Selectors

It is possible to apply a style for a selector within a selector.
In the example below, one style is specified for all p elements, one style is specified for all elements with class="marked", and a third style is specified only for p elements within elements with class="marked":

Example

<html>
<head>
<style type="text/css">
p
{
color:blue;
text-align:center;
}
.marked
{
background-color:red;
}
.marked p
{
color:white;
}
</style>
</head>

<body>
<p>This is a blue, center-aligned paragraph.</p>
<div class="marked">
<p>This p element should not be blue.</p>
</div>
<p>p elements inside a "marked" classed element keeps the alignment style, but has a different text color.</p>
</body>
</html>

Try it yourself in Notepad or Dreamweaver by coping and pasting the code above.

Leave a Reply