This content originally appeared on DEV Community and was authored by Aravind Sanjeev
Combinators in CSS are used to combine multiple CSS selectors. Combinators can be used in creative ways to select large groups of elements or increase specificity. The four types of combinators are,
- Descendant combinator (space)
- Child combinator (>)
- General sibling combinator (~)
- Adjacent sibling combinator (+)
Watch video instead:
Descendant combinator
Descendant combinator is simply the space character. As the name implies, it selects the descendants.
div p {
color: red;
}
The above CSS selects all paragraph that are descendants of div
element. You can combine multiple descendant combinators to increase specifcity. CSS rules are overrided depending on specifcity.
Child combinator
Child combinator selects the direct children of the parent combinator.
div > p {
color: red;
}
The difference between above two codes is that the the first one will select all paragraph elements that comes under a div. The second one will only select the direct children. So if there are paragraphs nested inside some other tags, styles won't be applied to them.
General sibling combinator
General sibling combinator selects all elements that comes after a specified element.
div ~ p {
color: red;
}
The above CSS will select all paragraphs that comes after a div. It doesn't matter even if there is other html tags in between. All paragraphs the comes after a div will be selected.
Adjacent sibling combinator
Adjacent sibling combinator selects the element that comes after a specified element.
div + p {
color: red;
}
The above CSS selects all paragraphs that comes just after a div. This is useful for spacing purposes. For example, if you want to add space on top of images that comes just after a section.
This content originally appeared on DEV Community and was authored by Aravind Sanjeev
Aravind Sanjeev | Sciencx (2021-12-19T21:12:58+00:00) Gentle Explanation for CSS Combinators. Retrieved from https://www.scien.cx/2021/12/19/gentle-explanation-for-css-combinators/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.