How to use CSS Combinators with examples

How to use CSS Combinators with examples

I continue fixing my CSS weakness, and today is time for the CSS Combinators.

Sometimes, we want to select elements without affecting others and understand the critical relationship between elements.

The CSS Combinators help to write a better CSS selector using the relation as key. We have four types of Combinators.

  • Descendant selector
  • Child Selector
  • Sibling Selector
  • General Sibling

The Descendant selector

It matches all elements that are descendants of the element.

My example, we have 2 div with the sandbox class and contains p and additional divs with p.

 <div class="sandbox">
        <p>hello</p>
      <div class="actions">
        <p>close</p>
      </div>
    </div>
     <div class="sandbox">
        <p>adios</p>
      <div class="actions">
        <p>close</p>
      </div>
    </div>

For set the background color to all p inside of sandbox.

.sandbox p {
 background-color: red;
}

it works, but not 100%, because others p inside of actions div have the background color.

So, If we want a rule that selects all dependents elements, use the descendant's selector.

But if I want only the p of the sandbox and skip the others, then the child selector comes to the rescue.

Child Selector (>)

The Child Selector use > and only select all direct children of the selector, so we can get our goal of only establishing the p of the sandbox.

.sandbox > p {
  background-color: red;
}

Nice, let continue!

Let's add more stuff into my sandbox, h2, and a few spans.

I want to select only the first span close to my h2.

<div class="sandbox">
    <h2>
      Angular 11
    </h2>
    <span>
      Google Framework.
    </span>
    <span>ngInit</span>
    <span>Observable</span>
    <p>hello</p>

    <div class="actions">
      <p>close</p>
    </div>
  </div>
....

Sibling Selector

The Sibling selector use + and select the next element in place of the selector. In our case, h2 span takes the first span close to h2.

h2 + span {
    background-color: pink;
    display: block;
    border-radius: 5px;
}

Work! But if I want all the remaining span close first to have another look? Tok General Sibling!

General Sibling Selector

The General Sibling use ~ and select all siblings placed after it, so we want all spans close to span to have another look, but my first span keeps his style.

span ~ span {
    background-color: gray;
    display: block;
}

{% jsfiddle jsfiddle.net/danywalls4/qyxp1t52/21 result,html,css %}

That's it! That will give you a bit of help with CSS Combinators. If you enjoyed this post, share it and Read more in MDN

Photo by Natalie Grainger on (Unsplash)