Skip to main content

CSS Combinators

CSS combinators are used to select elements based on their relationship to other elements. There are four types of CSS combinators:

Descendant selector (space)

The descendant selector is used to select all elements inside another element.

As an example:

  /* styles for all <p> elements inside .container */
}

Child selector (>)

The child selector is used to select all direct children of an element.

As an example:

.container > p {
/* styles for all <p> elements that are direct children of .container */
}

Adjacent sibling selector (+)

The adjacent sibling selector is used to select the element immediately after another element.

As an example:

h2 + p {
/* styles for the first <p> element after every <h2> element */
}

General sibling selector (~)

The general sibling selector is used to select all siblings that come after an element.

As an example:

h2 ~ p {
/* styles for all <p> elements that come after every <h2> element */
}

These combinators can also be combined with other CSS selectors to create more specific styles.

As an example:

.container .special p {
/* styles for all <p> elements inside .container with the .special class */
}

And the child selector can be combined with an ID selector to target a specific element that is a direct child of another element.

As an example:

#container > #special {
/* styles for the element with the ID of "special" that is a direct child of the element with the ID of "container" */
}