CSS Combinators

ADVERTISEMENT

Combinators connect selectors to define relationships between elements in the HTML structure. They help you target elements based on how they’re nested or placed next to each other.

🧩 Types of CSS Combinators

CombinatorSymbolMeaning
Descendant(space)Any nested element
Child>Direct children only
Adjacent Sibling+Next immediate sibling
General Sibling~All following siblings

✅ 1. Descendant Selector

div p {
  color: red;
}

Targets all <p> inside any <div>, no matter how deep.

<div>
  <section>
    <p>This will be red</p>
  </section>
</div>

✅ 2. Child Selector

ul > li {
  list-style-type: square;
}

Only targets <li> that are direct children of <ul>.

<ul>
  <li>✅ Direct child</li>
  <ol><li>❌ Not affected</li></ol>
</ul>

✅ 3. Adjacent Sibling Selector

h1 + p {
  font-weight: bold;
}

Targets the first <p> immediately after an <h1>.

<h1>Title</h1>
<p>✅ This is bold</p>
<p>❌ This is not</p>

✅ 4. General Sibling Selector

h2 ~ p {
  color: blue;
}

Targets all <p> siblings that follow an <h2>.

<h2>Section</h2>
<p>✅ Blue</p>
<p>✅ Also blue</p>

🔍 Quick Summary

CombinatorExampleSelects…
Spacediv pAny <p> inside <div>
>ul > liDirect children only
+h1 + pFirst immediate sibling
~h2 ~ pAll siblings that follow

⚠️ Tips

  • Combine combinators for specific layouts.
  • Use child selectors (>) to avoid unwanted deep nesting.
  • Use adjacent/general sibling selectors for form styling, layouts, and messages.

ADVERTISEMENT