HTML & CSS - Mastery / CSS Selectors

Combinator Selector(select elements based on a specific relationship between them)

Master Code Block (This will be used for further examples)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Selectors Example</title>
  </head>
  <body>
    <!--All content to be added here-->
  </body>
</html>

✅ 1. Descendant Selector (space)

Selects all elements inside another element, no matter how deeply nested.

div p is a descendant selector that selects all <p> elements inside a <div> (at any nesting level) and applies color: green;; the <p> outside the <div> (even though it's inside <body>) is not affected because it isn't a descendant of the <div>.


✅ 2. Child Selector (>)

Selects only the direct children of a specified element.

div > p is a child selector that selects only the <p> elements that are direct children of a <div> and applies color: blue;; the nested <p> inside <section> and the <p> outside the <div> are not affected.


✅ 3. Adjacent Sibling Selector (+)

Selects the element that is the immediate next sibling of another.

h1 + p is an adjacent sibling selector that selects only the first <p> immediately after an <h1> and applies color: red;; any later <p> or a <p> inside another element (like <div>) is not affected.


✅ 4. General Sibling Selector (~)

Selects all sibling elements that come after the specified element (not just the immediate one).

h1 ~ p is a general sibling selector that selects all <p> elements that are siblings and come after an <h1> and applies color: orange;; <p> elements inside another element (like <div>) or those that are not siblings of the <h1> are not affected.


🧾 Summary Table

Combinator

Meaning

Example

Description

(space)

Descendant

div p

All <p> inside <div>

>

Direct Child

div > p

Only immediate <p> children of <div>

+

Adjacent Sibling

h1 + p

The first <p> right after an <h1>

~

General Sibling

h1 ~ p

All <p>s after <h1> in the same parent