CSS Combinators

Home / CSS / CSS Combinators

CSS Combinators


CSS-Combinators:

CSS combinators are used to define relationships between different HTML elements when selecting them with CSS selectors. They allow you to target elements based on their relationship to other elements in the HTML document. There are several types of CSS combinators:

Descendant combinator (space):

Syntax: A B

Selects all elements B that are descendants of element A, no matter how deeply nested.

Example: div p selects all <p> elements that are descendants of <div> elements.

Child combinator (>):

Syntax: A > B

Selects all elements B that are a direct child of element A.

Example: ul > li selects all <li> elements that are direct children of <ul> elements.

Adjacent sibling combinator (+):

Syntax: A + B

Selects element B that is immediately preceded by element A and shares the same parent.

Example: h2 + p selects the first <p> element that directly follows an <h2> element.

General sibling combinator (~):

Syntax: A ~ B

Selects all elements B that are siblings of element A and share the same parent, coming after A.

Example: h2 ~ p selects all <p> elements that are siblings of an <h2> element.