Skip to content

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.

css
/* Selects all p elements inside div elements */
div p {
  color: red;
}
html
<div>
  <p>This paragraph is red.</p>
  <section>
    <p>This paragraph is also red because it is a descendant of the div.</p>
  </section>
</div>
<p>This paragraph is not red.</p>

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>.

css
/* Selects only p elements that are direct children of div */
div > p {
  color: blue;
}
html
<div>
  <p>This paragraph is blue because it is a direct child of the div.</p>
  <section>
    <p>This paragraph is not blue because it is not a direct child of the div.</p>
  </section>
</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.

css
/* Selects the p element immediately following an h1 */
h1 + p {
  margin-top: 0;
  font-style: italic;
}
html
<main>
  <h1>A Heading</h1>
  <p>This paragraph will have the style applied.</p>
  <p>This paragraph will not have the style applied.</p>
  <div>
    <p>This paragraph will also not have the style applied because it is not a sibling of the h1.</p>
  </div>
</main>

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.

css
/* Selects all sibling p elements following an h1 */
h1 ~ p {
  color: green;
}
html
<main>
  <h1>A Heading</h1>
  <div>This is a div</div>
  <p>This paragraph is green.</p>
  <p>This paragraph is also green.</p>
</main>

Mastering these combinators allows you to avoid creating unnecessary classes or IDs and write cleaner, more semantic CSS.

Content is for learning and research only.