CSS grouping and nesting


CSS Grouped and Nested Selectors


Grouped Selectors

There are many elements with the same style in the style sheet.

h1
{
color:green;
}
h2
{
color:green;
}
p
{
color:green;
}

To minimize code, you can use grouped selectors.

Separate each selector with a comma.

In the following example, we use grouped selectors for the above code:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
<style>
h1,h2,p
{
	color:green;
}
</style>
</head>

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

Run instance»

Click the "Run instance" button to view the online instance


Nested selector

It may apply to the style of the selector inside the selector.

In the following example, three styles are set:

  • p{ }: Specify a style for all p elements

  • .marked{ }: Specify a style for all elements with class="marked"

  • .marked p{ }: Specify a style for p elements within all class="marked" elements style.

  • p.marked{ }: Specify a style for all p elements with class="marked".

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
<style>
p
{
	color:blue;
	text-align:center;
}
.marked
{
	background-color:red;
}
.marked p
{
	color:white;
}
</style>
</head>

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

Run Instance»

Click the "Run Instance" button to view the online instance