HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

CSS Combinators

A combinator is something that explains the relationship between selectors. It allows you to select elements based on their position in the HTML document tree.


The Four Different Combinators

There are four different ways to combine selectors in CSS:

1. Descendant Selector (space)

Matches all elements that are descendants of a specified element (children, grandchildren, etc.).

div p {
    background-color: yellow;
}

2. Child Selector (>)

Selects elements that are a direct child of a specified element. It ignored grandchildren.

div > p {
    background-color: yellow;
}

3. Adjacent Sibling Selector (+)

Used to select an element that is directly after another specific element. The elements must share the same parent.

div + p {
    background-color: yellow;
}
/* Selects p element immediately following a div */

4. General Sibling Selector (~)

Selects all elements that are siblings of a specified element, even if they are not immediately following it.

div ~ p {
    background-color: yellow;
}
/* Selects all p elements that are siblings of a div */

Tip: Combinators make your CSS much cleaner. Instead of adding classes to every element, you can target specific elements based on their structure (e.g., targeting only paragraphs inside an article).