CSS combinators are selectors that allow you to select elements based on their relationship with other elements in the document tree. There are four types of CSS combinators:
- Descendant combinator (space) – It selects all the elements that are descendants of a specified ancestor. The syntax is:
ancestor descendant {
/* CSS rules */
}
For example, to select all the p
elements that are descendants of a div
element, you would use:
div p {
/* CSS rules */
}
Child combinator (>) – It selects only the direct children of the specified parent element. The syntax is:
parent > child {
/* CSS rules */
}
For example, to select all the li
elements that are direct children of a ul
element, you would use:
ul > li {
/* CSS rules */
}
- Adjacent sibling combinator (+) – It selects the element immediately following the specified element. The syntax is:
element1 + element2 {
/* CSS rules */
}
For example, to select the span
element that immediately follows a div
element, you would use:
div + span {
/* CSS rules */
}
- General sibling combinator (~) – It selects all the sibling elements that come after the specified element. The syntax is:
element1 ~ element2 {
/* CSS rules */
}
For example, to select all the p
elements that come after a h2
element, you would use:
h2 ~ p {
/* CSS rules */
}
These combinators allow you to target specific elements and create complex CSS rules by combining selectors.
Here are some additional examples of how combinators can be used in CSS:
- To select all the
em
elements that are descendants of ap
element that is a child of adiv
element, you would use:
div > p em {
/* CSS rules */
}
- To select the
label
element that immediately precedes aninput
element, you would use:
input + label {
/* CSS rules */
}
- To select all the
li
elements that come after the firstli
element in aul
element, you would use:
ul li ~ li {
/* CSS rules */
}
By using combinators, you can create more specific and targeted CSS rules that apply to only the elements that you want to style. This can help you create more complex layouts and designs that are easier to maintain and update over time.