CSS combinators are used to define relationships between elements in CSS. They allow you to select elements based on their relationship with other elements. The most commonly used combinators are:
The descendant combinator (a space) selects elements that are descendants of another element. For example:
div p {
color: red;
}
This is a paragraph inside a div element. It will be red.
The child combinator (>) selects elements that are direct children of another element. For example:
ul > li {
color: blue;
}
The adjacent sibling combinator (+) selects an element that is immediately preceded by a specified element. For example:
h1 + p {
color: green;
}
This paragraph is immediately after the h1 element. It will be green.
This paragraph is not immediately after the h1 element, so it will not be green.
The general sibling combinator (~) selects all elements that are siblings of a specified element. For example:
h1 ~ p {
color: orange;
}
This paragraph and all subsequent paragraphs will be orange.
This paragraph will also be orange because it follows the h1 element.