CSS combinators are used to explain a relationship between two selectors.
Types of CSS Combinators
There are four different types of combinators used in CSS:
- Descendant Selector (Space)
- Child Selector (>)
- Adjacent Sibling Selector (+)
- General Sibling Selector (~)
Descendant Selector (Space)
The descendant selector is used to select all the child elements of the specified element.
Example of Descendant Selector
div p {
background-color: #00758F;
color: #fff;
}
Output
Hello! This is the paragraph 1
Hello! This is the paragraph 2
Hello! This is the paragraph 3
Hello! This is the paragraph 4
Child Selector (>)
The child selector is used to select all the elements that are the children of the specified element.
Example of Child Selector
div > p {
background-color: #00758F;
color: #fff;
}
Output
Hello! This is the paragraph 1
Hello! This is the paragraph 2
Hello! This is the paragraph 3
Hello! This is the paragraph 4
Hello! This is the paragraph 5
Hello! This is the paragraph 6
Hello! This is the paragraph 7
Adjacent Sibling Selector (+)
The adjacent sibling selector is used to select all the elements that are the adjacent sibling of the specified element.
NOTE: The sibling elements must have the same parant element.
Example of Adjacent Sibling Selector
div + p {
background-color: #00758F;
color: #fff;
}
Output
Hello! This is the paragraph 1; paragraph inside the div
Hello! This is the paragraph 2; paragraph inside the div
Hello! This is the paragraph 3; paragraph outside the div
Hello! This is the paragraph 4; paragraph outside the div
General Sibling Selector (~)
The general sibling selector is used to select all the elements that are sibling of the specified element.
Example of General Sibling Selector
div ~ p {
background-color: #00758F;
color: #fff;
}
Output
Hello! This is the paragraph 1
Hello! This is the paragraph 2
Hello! This is the paragraph 3
Hello! Write here something
Hello! This is the paragraph 4