DEV Community

Cover image for CSS Combinators Explained.
Felix DUSENGIMANA
Felix DUSENGIMANA

Posted on • Updated on

CSS Combinators Explained.

When selecting HTML elements, sometimes it can be a little tricky to figure out which element you've selected. In this article, we'll provide an explanation of CSS combinators, making them easier to understand. Yeah, you've heard it, explained in an easy way.

CSS Combinators explains the relationship between CSS selectors, well I think you know what selectors are, if not consider reading this article. As the name says they combine different CSS selectors to provide useful relationships with each other.

Well, let's not take too long.

HTML code.

<div class="box">
     <p>Text in box</p>
      <section>
          <p>Text in box inside section</p>
    </section>
</div>
<div>
  <h1>Heading inside div.</h1>
  <p>Text in div not in box</p>
</div>
<p>Text 1 not both div and box</p>
<p>Text 2 not both div and box</p>
Enter fullscreen mode Exit fullscreen mode

1. Descendant combinator

The descendant selector matches all elements that are descendants (children, grandchildren, and so on) of a specified element. We use space between selectors.

The following example selects all <p> elements inside <div> elements:

div p{
color: red;
}
Enter fullscreen mode Exit fullscreen mode

Output:
Image description

2. Child combinator (>)

The child selector selects all elements that are direct descendants (children only) of a specified element. We use greater-than sign (>) between selectors.

The following example selects all <p> elements that are children of a <div> element:

div > p{
color: red;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

3. Adjacent sibling combinator (+)

The adjacent sibling selector is used to select an element that immediately follows another specific element. Sibling elements must have the same parent element. We use plus sign (+) between selectors.

The following example selects the first <p> element that are placed immediately after <div> elements:

div + p{
color: red;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

4. General sibling combinator (~)

The general sibling selector selects all elements that are next siblings of a specified element.
We use tilde sign (~) between selectors.

The following example selects all

elements that are next siblings of

elements:
div ~ p{
color: red;
}

Output:

Image description

Let's connect:

Twitter
GitHub

Discussion (0)