Selectors in CSS

Selectors in CSS

Two articles have been published till now where I explained about the CSS Selectors. Here are the links to those articles:

This is the continuation and last article of the series where I will be explaining about the selector called combinators.

Let's jump straight into the topic now.

1. Descendant combinator

The descendant combinator selects the descendants of the given element and has space in between the elements to be selected.

Let's understand this with a simple example:

<div>
       <p>First paragraph</p>
  <ul>
       <p>Second paragraph inside unordered list</p>
  </ul>
</div>
<p>Third paragraph</p>
div p { color: red;}

Output

Screenshot (15).png

In the example above, both first and second paragraphs are selected as both are under div and third paragraph is not selected because it is outside the div.

2. Child combinator

The child combinator (>) selects the direct children of a given element. Let's take the above example again.

<div>
       <p>First paragraph</p>
  <ul>
       <p>Second paragraph inside unordered list</p>
  </ul>
</div>
<p>Third paragraph</p>
div > p { color: red;}

Output

Screenshot (16).png

Did you spot the difference between descendant combinator and child combinator?

3. Adjacent sibling combinator

Adjacent sibling combinator (+) is used to select an element that is immediately after the closing of a specific element.

Let's understand this via an example:

<div>
  <p>First paragraph</p>
  <div>
    <p>Second paragraph</p>
  </div>
  <p>Third paragraph</p>
  <p>Fourth paragraph</p>
</div>
div + p {
  background: green;
}

Output

Screenshot (19).png

4. General sibling combinator

Unlike adjacent sibling selectors, the general sibling selector selects all those siblings which come after the specified element even if there are some other elements in between.

Let's make this crystal clear by considering this example :

<div>
  <p>First paragraph</p>
  <div>
    <p>Second paragraph</p>
  </div>
  <p>Third paragraph</p>
  <span>I am an span element</span>
  <p>Fourth paragraph</p>
</div>
div ~  p {
  background: green;
}

Output

Screenshot (20).png

So, this is the wrap up of the series CSS Selectors. I hope you enjoyed the article.

Thank you for reading.