CSS combinators are used to define the relationship between two selectors. Understanding CSS combinators helps in creating more precise and effective CSS rules. There are four types of combinators in CSS: descendant combinator, child combinator, adjacent sibling combinator, and general sibling combinator.
The descendant combinator is represented by a space between two selectors. It targets elements that are descendants of a specified element.
For example, the following CSS rule selects all <p> elements that are descendants of a <div> element:
div p {
color: blue;
}
In this example, all <p> elements within any <div> will be styled according to the CSS rule.
The child combinator is represented by a greater-than sign (>
) between two selectors. It targets elements that are direct children of a specified element.
For example, the following CSS rule selects all <p> elements that are direct children of a <div> element:
div > p {
color: green;
}
In this example, only the <p> elements that are direct children of a <div> will be styled according to the CSS rule.
The adjacent sibling combinator is represented by a plus sign (+
) between two selectors. It targets an element that is immediately preceded by a specified element.
For example, the following CSS rule selects the <p> element that immediately follows a <h1> element:
h1 + p {
color: red;
}
In this example, the first <p> element immediately following a <h1> will be styled according to the CSS rule.
The general sibling combinator is represented by a tilde (~
) between two selectors. It targets all elements that are siblings of a specified element.
For example, the following CSS rule selects all <p> elements that are siblings of a <h1> element:
h1 ~ p {
color: purple;
}
In this example, all <p> elements that are siblings of a <h1> will be styled according to the CSS rule.
Understanding the differences between these combinators helps you create more efficient and specific CSS rules. Here are comparisons of the different combinators:
Here are some important notes and best practices when using CSS combinators: