CSS Combinators - Detailed Overview

Introduction to CSS Combinators

CSS combinators are used to define relationships between elements in CSS. They allow you to select elements based on their relationship with other elements. The most commonly used combinators are:

Descendant Combinator

The descendant combinator (a space) selects elements that are descendants of another element. For example:

div p {
    color: red;
}
This is a div element.

This is a paragraph inside a div element. It will be red.

Child Combinator

The child combinator (>) selects elements that are direct children of another element. For example:

ul > li {
    color: blue;
}
  • This is a direct child of the ul element. It will be blue.
  • This is another direct child of the ul element. It will be blue.
  • This is not a direct child of ul, so it will not be blue.

Adjacent Sibling Combinator

The adjacent sibling combinator (+) selects an element that is immediately preceded by a specified element. For example:

h1 + p {
    color: green;
}

This is an h1 element.

This paragraph is immediately after the h1 element. It will be green.

This paragraph is not immediately after the h1 element, so it will not be green.

General Sibling Combinator

The general sibling combinator (~) selects all elements that are siblings of a specified element. For example:

h1 ~ p {
    color: orange;
}

This is an h1 element.

This paragraph and all subsequent paragraphs will be orange.

This paragraph will also be orange because it follows the h1 element.