CSS-Combinators

There are four different combinators in CSS:

1. descendant selector (space)

2. child selector (>)

3. adjacent sibling selector (+)

4. general sibling selector (~)

1)  Child selectors:

<div>
    <p>Paragraph 1 in the div.</p>
    <p>Paragraph 2 in the div.</p>
      <section>
            <!-- not Child but Descendant -->
         <p>Paragraph 3 in the div (inside a section element).</p>
      </section>
    <p>Paragraph 4</p>   <!--Not in a div-->
</div>
    <p>Paragraph 5.</p>      <!--Not in a div-->
    <p>Paragraph 6.</p>      <!--Not in a div-->


<style>
    div>p {
        background-color: yellow;
    }
</style>

The child selector (>) selects all elements that are the children of that specific element.
2)  Descendant Selector:
<style>
div p {
  background-color: yellow;
}
</style>

<div>
  <p>Paragraph 1 in the div.</p>
  <p>Paragraph 2 in the div.</p>
  <section><p>Paragraph 3 in the div.</p></section>
</div>

<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>

The descendant selector matches all elements that are descendants of that specific element.

3)  Adjacent Sibling Selector (+):

<div>
  <p>Paragraph 1 in the div.</p>
  <p>Paragraph 2 in the div.</p>
</div>

<p>Paragraph 3. After a div.</p>
<p>Paragraph 4. After a div.</p>

<div>
  <p>Paragraph 5 in the div.</p>
  <p>Paragraph 6 in the div.</p>
</div>

<p>Paragraph 7. After a div.</p>
<p>Paragraph 8. After a div.</p>

<style>
    div + p {
     background-color: yellow;
    }
</style>

The adjacent sibling selector is used to select an element that is directly after another specified element.

4)  General Sibling Selector (~):

<p>Paragraph 1.</p>
<div>
    <p>Paragraph 2.</p>
</div>
<p>Paragraph 3.</p>
<code>Some code.</code>
<p>Paragraph 4.</p>


<style>
    div ~ p {
        background-color: yellow;
    }
</style>
The general sibling selector selects all elements that are next siblings of a specific element.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories