What combinator selectors should I be familiar with?

Question

What combinator selectors should I be familiar with?

Answer

Developers will see descendant and child combinator selectors often, but should also be familiar with adjacent sibling and general sibling combinator selectors.

Examples of each:

/* Descendant Selector - will target all elements with a class of "my-class" 
that are a descendant of a <div> element (including a direct child, 
children of children, etc) */
div .my-class {
  ...
}

/* Child Selector - will target any elements with a class of 
"another-class" that are a direct child of a <p> element */
p > .another-class {
  ...
}

/* Adjacent Sibling Selector - will target any <div> element that is the
next sibling of an element with an id of "unique-id" */
#unique-id + div {
  ...
}

/* General Sibling Selector - will target any <p> elements that are the
next siblings of an element with a class of "class-name" */
.class-name ~ p {
  ...
}
1 Like

Hello,

Could you help clarify the CSS selectors you mentioned by providing HTML examples of what those combinations look like?

Thank you very much.

1 Like
div .my-class
<div>
<p class="my-class">A descendant of DIV</p>
</div>
p > .another-class
<p>A paragraph with a <span class="another-class">direct child</span></p>
#unique-id + div
<div id="unique-id">

</div>
<div>
<!-- selects this adjacent sibling IF it is a DIV -->
</div>
.class-name ~ p
<div class="class-name">Not this one</div>
<p>This one</p>
<p>This one</p>
<p>This one</p>

Be sure to verify this with some follow up reading.

8 Likes

Beautifully illustrated, thank you !!

2 Likes

I tried to type this without a space between div and .my-class and it didn’t work. After I added the space, it worked. Why do we need a space in between div and .my-class?
And in this exercise, it needs a space between article and .receipe? Thanks.

article .recipe {
font-weight: bold;
}

this post helps me a lot ! thanks!

If you don’t add a space between div and .my-class, the selector is targeting a different element. div.my-class will select all the <div> elements with a class of my-class while div .my-class selects all the elements with a class of my-class that are descendants of a <div> element. The same thing applies with the article .recipe and article.recipe selectors

type.class       =>  specific selector

type .class      =>  child combinator

type > .class    =>  direct child combinator
1 Like