MyInternships.in

CSS Tutorial

CSS Combinators

Combinators are the symbols between two selectors that describe the relationship between elements. They let you target elements based on where they sit in the HTML tree — inside, directly inside, or next to another element.


What are combinators?

A combinator joins two selectors and tells the browser how the elements must be related for the rule to apply. CSS has four: the descendant combinator (a space), the child combinator (>), the adjacent sibling combinator (+), and the general sibling combinator (~).

CombinatorSyntaxMatches
Descendantdiv pEvery <p> anywhere inside a <div>
Childdiv > pOnly <p> that is a direct child of <div>
Adjacent siblingh2 + pThe first <p> immediately after an <h2>
General siblingh2 ~ pEvery <p> sibling that follows an <h2>

Descendant vs child

The descendant combinator reaches any level deep, while the child combinator only matches direct children. In the demo, the descendant rule colours every paragraph inside the box, but the child rule colours only the paragraph that is a direct child.

Example
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: system-ui, sans-serif; padding: 16px; }
  .box p        { color: #16a34a; }   /* descendant: any depth */
  .box > p      { font-weight: bold; } /* child: direct only */
</style>
</head>
<body>
  <div class="box">
    <p>Direct child — green and bold.</p>
    <section>
      <p>Nested paragraph — green but NOT bold.</p>
    </section>
  </div>
</body>
</html>

Adjacent vs general sibling

The adjacent sibling combinator (+) matches only the one element immediately after another, while the general sibling combinator (~) matches all following siblings. Both require the elements to share the same parent.

Example
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: system-ui, sans-serif; padding: 16px; }
  h4 + p { color: #dc2626; }    /* first p right after h4 */
  h4 ~ p { background: #fef9c3; } /* every p after h4 */
</style>
</head>
<body>
  <h4>Heading</h4>
  <p>First paragraph — red text AND yellow background.</p>
  <p>Second paragraph — only yellow background.</p>
  <p>Third paragraph — only yellow background.</p>
</body>
</html>
💡

The space combinator is easy to miss. div p (with a space) is completely different from divp; the space is the descendant combinator itself.

Key points

  • Descendant (space) matches elements at any depth inside an ancestor.
  • Child (>) matches only direct children.
  • Adjacent sibling (+) matches the single element immediately after another.
  • General sibling (~) matches all following siblings with the same parent.

Related CSS Topics

Keep learning with these closely related tutorials.

Ready to use your CSS skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships