CSS combinators are used to define the relationship between selectors. They help in applying styles to elements based on their relationship in the HTML document.
There are four main types of combinators:
- descendant combinator
- child combinator
- adjacent sibling combinator
- general sibling combinator
1. Descendant Combinator ()
The descendant combinator selects elements that are descendants of a specified element. This is represented by a space between two selectors.
Example: Selects all <p> elements inside elements.
/* Selects all <p> elements inside <div> elements */
div p {
color: blue;
}
2. Child Combinator (>
)
The child combinator selects elements that are direct children of a specified element.
Example: Selects all <p> elements that are direct children of <div> elements
/* Selects all <p> elements that are direct children of <div> elements */
div > p {
color: green;
}
3. Adjacent Sibling Combinator (+
)
The adjacent sibling combinator selects an element that is directly adjacent to a specified element. This means it selects the element that immediately follows the first element.
Example: Selects the <p> element that is immediately after a <div> element
/* Selects the <p> element that is immediately after a <div> element */
div + p {
color: red;
}
4. General Sibling Combinator (~
)
The general sibling combinator selects all elements that are siblings of a specified element, following it.
Example: Selects all <p> elements that are siblings of a <div> element
/* Selects the <p> Selects all <p> elements that are siblings of a <div> element */
div ~ p {
color: orange;
}
Complete Example:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
/* Descendant Combinator */
div p {
color: blue;
}
/* Child Combinator */
div > p {
color: green;
}
/* Adjacent Sibling Combinator */
div + p {
color: red;
}
/* General Sibling Combinator */
div ~ p {
color: orange;
}
</style>
</head>
<body>
<div>
<p>Descendant (and child) of div</p>
<p>Another descendant (and child) of div</p>
</div>
<p>Adjacent sibling of div</p>
<p>General sibling of div</p>
</body>
</html>
Explanation:
- Descendant Combinator (
div p
): Styles all<p>
elements inside a<div>
, regardless of their depth. - Child Combinator (
div > p
): Styles only<p>
elements that are direct children of a<div>
. - Adjacent Sibling Combinator (
div + p
): Styles the first<p>
element immediately following a<div>
. - General Sibling Combinator (
div ~ p
): Styles all<p>
elements that are siblings of a<div>
and come after it.