Table of Contents
Combinator selectors
The Combinator selectors select elements based on a specific relationship between them.
There are four different combinators selectors in CSS:
- Descendant selector (space)
- Child selector (>)
- Adjacent sibling selector (+)
- General sibling selector (~)
Descendant selector (space)
- It selector matches all elements that are descendants of a specified element.
Example
<!DOCTYPE html>
<html>
<head>
<style>
div p {
background-color: yellow;
}
</style>
</head>
<body>
<h2>Descendant selector (space)</h2>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<h3>This is a heading</h3>
<p>Paragraph 3 in the div.</p>
</div>
<p>Paragraph 4. Not in a div.</p>
</body>
</html>
Child selector (>)
- It selects all elements that are the children of a specified element.
Example
<!DOCTYPE html>
<html>
<head>
<style>
div > p {
background-color: yellow;
}
</style>
</head>
<body>
<h2>Child Selector</h2>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
<section>
<!-- not Child but Descendant -->
<p>Paragraph 3 in the div .</p>
</section>
<p>Paragraph 4 in the div.</p>
</div>
<p>Paragraph 5. Not in a div.</p>
</body>
</html>
Adjacent sibling selector (+)
- It selector selects all elements that are the adjacent siblings of a specified element
Example
<!DOCTYPE html>
<html>
<head>
<style>
div + p {
background-color: yellow;
}
</style>
</head>
<body>
<h2>Adjacent sibling selector (+)</h2>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
</div>
<p>Paragraph 3 After a div.</p>
<div>
<p>Paragraph 4 in the div.</p>
</div>
<p>Paragraph 5 After a div.</p>
</body>
</html>
General sibling selector (~)
- It selects all elements that are siblings of a specified element.
Example
<!DOCTYPE html>
<html>
<head>
<style>
div ~ p {
background-color: yellow;
}
</style>
</head>
<body>
<h2>General sibling selector (~)</h2>
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
</div>
<p>Paragraph 3 After a div.</p>
</body>
</html>