CSS Combinators
Combinators combine multiple simple selectors to select elements based on their specific relationship in the document tree. This allows us to write more precise and targeted CSS rules.
There are four main combinators in CSS.
1. Descendant Selector (Space)
The descendant selector is separated by a space . It selects all descendant elements nested inside the specified ancestor element, regardless of how deep the nesting is.
Syntax: ancestor descendant
Example: div p selects all <p> elements inside <div> elements.
2. Child Selector (>)
The child selector is separated by a greater-than sign >. It selects only elements that are direct children of the specified parent element.
Syntax: parent > child
Example: div > p selects only <p> elements whose parent is <div>.
3. Adjacent Sibling Selector (+)
The adjacent sibling selector is separated by a plus sign +. It selects the first sibling element that is immediately after the specified element. Both elements must share the same parent.
Syntax: element + target
Example: h1 + p selects all <p> elements that immediately follow an <h1> element.
4. General Sibling Selector (~)
The general sibling selector is separated by a tilde ~. It selects all sibling elements that follow the specified element. Both elements must share the same parent.
Syntax: element ~ target
Example: h1 ~ p selects all <p> elements that follow an <h1> element and share the same parent.
Mastering these combinators allows you to avoid creating unnecessary classes or IDs and write cleaner, more semantic CSS.