CSS Combinators
- Previous Page CSS Alignment
- Next Page CSS Pseudo-classes
CSS Combinators
Combinators are a mechanism that explains the relationship between selectors.
CSS selectors can contain multiple simple selectors. We can include a combinator between simple selectors.
There are four different types of combinators in CSS:
- Descendant Selector (space)
- Child Selector (
>
) - Adjacent Sibling Selector (
+
) - General Sibling Selector (
~
)
Descendant Selector
The descendant selector matches all elements that are descendants of the specified element.
The following example selects all <p> elements within the <div> element:
Example
div p { background-color: yellow; }
Child Selector
The child selector matches all elements that are children of the specified element.
The following example selects all <p> elements that are children of the <div> element:
Example
div > p { background-color: yellow; }
Adjacent Sibling Selector
The adjacent sibling selector matches all elements that are adjacent siblings of the specified element.
Sibling (same-level) elements must have the same parent element. 'Adjacent' means 'immediately following'.
The following example selects all <p> elements that immediately follow the <div> element:
Example
div + p { background-color: yellow; }
General Sibling Selector
The general sibling selector matches all elements that are siblings of the specified element.
The following example selects all <p> elements that are siblings of the <div> element:
Example
div ~ p { background-color: yellow; }
All CSS Combinator Selectors
Selector | Example | Example Description |
---|---|---|
element element | div p | Select all <p> elements within the <div> element. |
element>element | div > p | Select all <p> elements whose parent element is a <div> element. |
element+element | div + p | Select all <p> elements that immediately follow a <div> element. |
element1~element2 | p ~ ul | Select each <ul> element that has a preceding <p> element. |
Further Reading
Supplementary Books:CSS Descendant Selector
Supplementary Books:CSS Child Element Selector
Supplementary Books:CSS Adjacent Sibling Selector
- Previous Page CSS Alignment
- Next Page CSS Pseudo-classes