CSS combinators are explaining the relationship between two selectors. CSS selectors are the patterns used to select the elements for style purpose. A CSS selector can be a simple selector or a complex selector consisting of more than one selector connected using combinators.
There are four types of combinators available in CSS which are discussed below:
- General Sibling selector (~)
- Adjacent Sibling selector (+)
- Child selector (>)
- Descendant selector (space)
CSS Combinators- General sibling
The general sibling combinator (~
) separates two selectors and matches all iterations of the second element, that are following the first element (though not necessarily immediately), and are children of the same parent element.
div ~ p { background-color: hotpink; }
CSS Combinators -Adjacent sibling
The adjacent sibling selector (+
) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the next sibling element of the first selector. For example, to select all <img>
elements that are immediately preceded by a <p>
element
div + p { background-color: blue; }
CSS Combinators-child sibling
The child combinator (>
) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first. Descendent elements further down the hierarchy don’t match. For example, to select only <p>
elements that are direct children of <article>
elements
div > p { background-color: red; }
CSS Combinators-decendent
The descendant combinator — typically represented by a single space () character — combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent’s parent, parent’s parent’s parent, etc) element matching the first selector. Selectors that utilize a descendant combinator are called descendant selectors.
div p { background-color: yellow; }