CSS Combinators

CSS combinators are powerful tools that allow you to target specific elements on a webpage based on their relationship to other elements. There are four main types of combinators: descendant, child, adjacent sibling, and general sibling. Let's dive into each one with some examples.
Mandatory reading
To understand all the cases, see the CSS Selector reference

Descendant Combinator

The descendant combinator is denoted by a space between two selectors. It targets all elements that are descendants of a specified element. For example, let's say we want to target all p elements that are descendants of a div element:
div p {
  color: blue;
}
This CSS rule will make all p elements inside a div element have blue text.

Child Combinator

The child combinator is denoted by a greater than sign (>) between two selectors. It targets only the immediate children of a specified element. For example, let's say we want to target all p elements that are direct children of a div element:
div > p {
  font-weight: bold;
}
This CSS rule will make all p elements that are immediate children of a div element bold.

Adjacent Sibling Combinator

The adjacent sibling combinator is denoted by a plus sign (+) between two selectors. It targets an element that is immediately preceded by a specified element. For example, let's say we want to target all p elements that are immediately preceded by an h2 element:
h2 + p {
  margin-top: 20px;
}
This CSS rule will add a top margin of 20 pixels to all p elements that are directly preceded by an h2 element.

General Sibling Combinator

The general sibling combinator is denoted by a tilde sign (~) between two selectors. It targets all elements that are siblings of a specified element, following it in the HTML document. For example, let's say we want to target all p elements that are siblings of an h2 element:
h2 ~ p {
  color: green;
}
This CSS rule will make all p elements that are siblings of an h2 element have green text. By using these combinators, you can create more specific and targeted CSS rules for styling elements on your webpage. Experiment with different combinations to see how you can customize your website's design further.