Skip to content

CSS Combinators

There are few different kinds of CSS combinators available and the most commonly used of them are: 1. Descendant combinator 2. Child combinator 3. Adjacent Sibling Combinator 4. General Sibling Combinator

Read more about CSS Combinators

Descendant Combinator

Descendant combinator targets all element(s) inside another element(s). You separate the selector with spaces.

Example, targeting only <p> element inside our <header> section:

CSS
/* 1/4: Descendant combinator */
/* Targets all elements inside the parent element */
header p {
  font-weight: bold;
  color: gray;
}

Example, targeting only <span> element inside our <header>'s <p> section:

CSS
header p span {
  color: red;
}

Child Combinator

Child combinator targets only the element(s) that are directly under the targeted element.

Example, targeting only <p> elements under the header section:

CSS
/* 2/4: Child Combinator */
/* Targets only elements directly under the parent element */
header > p {
  font-size: 22px;
}

Adjacent Sibling Combinator

Adjacent sibling combinator is used to target all elements that are in the same level and come directly after the specified element.

Example, targeting only <p> elements after the <h2> tag:

CSS
/* 3/4: Adjacent Sibling Combinator */
/* Targets all elements that are in the same level and come directly after the specified element. */
h2 + p {
  border: 1px solid black;
}

General Sibling Combinator

General sibling combinator can be used to select elements that come after the some element, even if they are not directly next to each other.

Example, targeting all <img> elements that come somewhere after the <p> tag:

CSS
/* 4/4: General Sibling Combinator */
/* Targets all elements after the first element, even if they do not come directly after the first element */
h2 ~ p {
  border: 3px solid red;
}

Combining the Combinators

You can freely combine these combinators as you like.

Example:

CSS
/* Combining the combinators */
body > footer > .text-light span  {
  color: gray;
  font-size: 12px;
}