CSS combinators are combinations of 2 or more CSS selectors.
These selectors have certain relationships with each other.
Relationship types are: descendent, child, adjacent, or sibling.
A parent-child relationship between 2 selectors (.contain > .child
).
<style>
.contain {
background-color: lightblue;
padding: 30px;
}
.contain > .child {
background-color: aliceblue;
padding: 15px;
}
</style>
<div class="contain">
<div class="child">A child element</div>
</div>
A combinator combines two selectors into a new relationship.
There are four different CSS combinators:
descendent selector (space)
child selector (>)
adjacent sibling selector (+)
general sibling selector (~)
A descendent selector matches two elements that are descendents from each other.
The descendent element can be any level below the ancestor.
This combinator uses a ' '
(space) between the selectors.
In this example the descendants are 4 levels deep and are styled correctly.
<style>
.ancestor {
background-color: lightblue;
padding: 15px;
}
.ancestor .descendent {
background-color: aliceblue;
padding: 30px;
margin: 10px;
}
</style>
<div class="ancestor">
<div>
<div>
<div class="descendent">Descendent element</div>
<div class="descendent">Descendent element</div>
<div class="descendent">Descendent element</div>
</div>
</div>
</div>
The child selector matches all immediate children of an element.
This relationship is only 1 level deep.
The combinator uses a '>
' between the selectors.
Only immediate child elements are assigned a style.
<style>
.the-parent {
background-color: lightblue;
padding: 30px;
}
.the-parent > div {
background-color: aliceblue;
padding: 30px;
margin: 20px 0;
}
</style>
<div class="the-parent">
<div>Immediate child element</div>
<div>Immediate child element</div>
<div>Immediate child element</div>
<section>
<div>Not an immediate child</div>
</section>
</div>
The adjacent sibling selector matches all elements that are adjacent sibling elements.
Sibling elements have the same parent and must follow each other immediately.
This combinator uses a '+
' between the selectors.
Only the element adjacent to the starting element is styled.
<style>
.adjacent {
background-color: lightblue;
padding: 30px;
}
.adjacent + div {
background-color: aliceblue;
padding: 30px;
margin: 20px 0;
}
</style>
<div>
<div class="adjacent">Starter</div>
<div>Adjacent sibling</div>
<div>Not an adjacent sibling</div>
<div>Not an adjacent sibling</div>
</div>
The general sibling selector matches all elements that follow the specified element and are siblings.
This combinator uses a '~
' between the selectors.
All sibling elements are styled.
<style>
.general {
background-color: lightblue;
padding: 30px;
}
.general ~ div {
background-color: aliceblue;
padding: 30px;
margin: 20px 0;
}
</style>
<div>
<div class="general">Starter</div>
<div>A general sibling</div>
<div>A general sibling</div>
<div>A general sibling</div>
</div>