A CSS selector can comprise multiple simple selectors, and between them, we can include a combinator.
CSS offers four distinct types of combinators:
The descendant selector targets all elements that are descendants of a specific element.
In the example below, it selects all <p> elements within <div> elements:
Example
div p { background-color: yellow; } |
The child selector picks all elements that are direct children of a specified element.
In this example, it selects all <p> elements that are direct children of a <div> element:
Example
div > p { background-color: yellow; } |
The adjacent sibling selector targets an element that directly follows another specific element.
For siblings to be considered adjacent, they must share the same parent element, and “adjacent” indicates “immediately following.”
In this example, it selects the first <p> element that immediately follows <div> elements:
Example
div + p { background-color: yellow; } |
The general sibling selector chooses all elements that are siblings following a specified element.
In this example, it selects all <p> elements that are siblings immediately following <div> elements:
Example
div ~ p { background-color: yellow; } |
Selector |
Example |
Example description |
element element |
div p |
Selects all `<p>` elements that are within `<div>` elements |
element>element |
div > p |
Selects all `<p>` elements that have a `<div>` element as their parent |
element+element |
div + p |
Selects the first `<p>` element that is immediately preceded by a `<div>` element |
element1~element2 |
p ~ ul |
Selects every `<ul>` element that is preceded by a `<p>` element |