What combinator selectors should I be familiar with?


#1

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 {
  ...
}