CSS Selectors
Grouped Selectors
There are many elements in stylesheets that share the same style.
h1 {
color: green;
}
h2 {
color: green;
}
p {
color: green;
}
To minimize code, you can use grouped selectors.
Each selector is separated by a comma.
In the example below, we use a grouped selector for the above code:
h1, h2, p {
color: green;
}
Nested Selectors
They may apply styles to selectors within selectors.
The example below sets four styles:
p { }
: Specifies a style for all p
elements.
.marked { }
: Specifies a style for all elements with class="marked"
.
.marked p { }
: Specifies a style for all p
elements within elements with class="marked"
.
p.marked { }
: Specifies a style for all p
elements with class="marked"
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Demonstration</title>
<style>
p {
color: blue;
text-align: center;
}
.marked {
background-color: red;
}
.marked p {
color: white;
}
p.marked {
text-decoration: underline;
}
</style>
</head>
<body>
<p>This is a regular paragraph, its color is blue, and the text is centered.</p>
<div class="marked">
<p>This is a paragraph within a div with class "marked", its background color is red, the text color is white, and the text is centered.</p>
</div>
<p class="marked">This is a paragraph with both the "p" tag and the "marked" class, its color is blue, underlined, and the text is centered.</p>
</body>
</html>