CSS combinators


A combinator is something that explains the relationship between the selectors.

A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.

There are four different combinators in CSS:

  • descendant selector (space)
  • child selector (>)
  • adjacent sibling selector (+)
  • general sibling selector (~)

In this lesson we will talk about two first compinators - descendant and child selectors.


Descendant Selector

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

The following example selects all <p> elements inside <div> with the class .parent-example elements: 



                .parent-example p {
                    background-color: yellow;
                  }
  
              


        <div class="parent-example">
            <p>Paragraph 1 in the div .parent-example.</p>
            <p>Paragraph 2 in the div .parent-example>.</p>
            <span>
                <p>Paragraph 3 in the div .parent-example.</p>
            </span>
        </div>

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

        

Live preview

Paragraph 1 in the div .parent-example.

Paragraph 2 in the div .parent-example.

Paragraph 3 in the div .parent-example.

Paragraph 4. Not in a div .parent-example.

Paragraph 5. Not in a div .parent-example.


Child Selector

The child selector selects all elements that are the immediate children of a specified element.

The following example selects all <p> elements that are immediate children of a <div> with the class .parent-example-2 element:



                  .parent-example-2 > p {
                    background-color: rgb(169, 169, 221);
                  }
  
              


                <div class="parent-example-2">
                    <p>Paragraph 1 in the div .parent-example-2.</p>
                    <p>Paragraph 2 in the div .parent-example-2.</p>
                    <span>
                        <p>Paragraph 3 in the div .parent-example-2 - it is descendant but not immediate child.</p>
                    </span> <!-- not Child but Descendant -->
                </div>

                <p>Paragraph 4. Not in a div .parent-example-2.</p>
                <p>Paragraph 5. Not in a div .parent-example-2.</p>

        

Live preview

Paragraph 1 in the div .parent-example-2.

Paragraph 2 in the div .parent-example-2.

Paragraph 3 in the div .parent-example-2 - it is descendant but not immediate child.

Paragraph 4. Not in a div.

Paragraph 5. Not in a div.


Previous lesson Next lesson

Spread the word:
Do you need help? Use our support forum

About the author

User avatar
Michal Szymanski
Co-Founder at MDBootstrap & BrandFlow. Entrepreneur, web developer, UI/UX designer, marketing analyst. Dancer and nerd in one.