Category Archives: CSS

All CSS Combinator Selectors

A useful CSS tip for selecting nested elements

This a handful table that shows how to combinator selectors works.

According to the w3schools, a combinator

“is something that explains the relationship between the selectors”

There are four combinators:

  • descendant selector which is represented by a space
  • child selector, with > signal
  • adjacent sibling selector, a + signal
  • general sibling selector, a ~ signal

Above, some examples

Consider the following HTML structure

<body>

<h2>Descendant Selector</h2>

<p>The descendant selector matches all elements that are descendants of a specified element.</p>

<div>
  <p>Paragraph 1 in the div.</p>
  <p>Paragraph 2 in the div.</p>
  <section><p>Paragraph 3 in the div.</p></section>
</div>

<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>

</body>

The descendant selector (white space) selects all elements that are descendant of a specified element. So, the next code will paint the three <p> elements inside the div with the yellow color, including the one inside the <section> element.

div p {
  background-color: yellow;
}

The child selector ( > ) selects all elements that are children of a specified element. So, the next code will paint the pair of <p> elements inside the div with the yellow color. But not the <p> inside the <section> because this element is not a child, but a descendant.

div > p {
  background-color: yellow;
}

The adjacent sibling selector ( + ) selects an element that is directly after another specific element. So, the next code will paint only the 4th <p> element, since it is the only directly after a <div>.

div + p {
  background-color: yellow;
}

The general sibling selector ( ~ ) selects all elements that are next siblings of a specified element. So, the next code will paint the last pair of <p> elements.

div ~ p {
  background-color: yellow;
}

CSS is intriguing technology with many cool features that can be applied to enhance a great variety of UI/UX proposes. And is very funny to learn.

I recommend the Advanced CSS and Sass course by Jonas Schmedtmann at Udemy.

Have fun.