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 {
...
}
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.
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
I´ve been playing with the child combinator for a bit and I came across an example on the MDN with a red border on list elements. Then I tried to add a color to that and ended up being confused why the rule got only applied to the border.
Can someone explain this to me (see screenshot attached)?
ul > li is selecting all of the li elements that are direct children of the ul element. The color property is inheritable by default, so not only do the direct children of the ul get a color of royalblue, but the children of the lis also get it
The border-top: 5px solid red declaration is setting the top border of the lis which are direct children of the ul to be 5 pixels, and red. As this property is not inheritable, the grandchildren elements of the ul won’t have a top border