DEV Community

Cover image for Deep dive into CSS selector combinations
Jay Rajput
Jay Rajput

Posted on

Deep dive into CSS selector combinations

In CSS, selectors are used to target the HTML elements we want to style. We can combine selectors to get meaningful relationship and target specific elements. Below are some of the less used but handy selector combinations:

  • Descendant combinator
  • Child combinator
  • Adjacent sibling
  • Child sibling

We will refers to below HTML code block for understanding combinator selectors.

HTML example

Descendant combinator

Descendant combinator selects a combination where the second selector is descendant for first selector. Second selector does not needs to be a direct descendant for first selector and is separated from first selector by a white-space.

.container p{
  color: orange;
}
Enter fullscreen mode Exit fullscreen mode

Here all the descendant paragraphs of the .container class will have the text colored orange.

descandant combinator

Child Combinator

This type of combinator selects only the element matched by the second selector that are direct children of first selector.

.container>p{
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode

After applying the above combinator only the paragraphs that are direct children of .container class will have background color of blue. Notice below that paragraph four is still the same since it is not a direct child of .container parent class.

Alt Text

Adjacent Sibling

This combination matches only second element that immediately follows the first element. The selectors are separated by "+" symbol and they both belong to the same parent element.

a + p{
  background-color: grey;
}
Enter fullscreen mode Exit fullscreen mode

After applying above combination, the paragraph that immediately follows the anchor tag (abc site in this case) will have a background color of grey.

Adjacent Selector

General Sibling

General sibling combinator matches the second elements that are adjacent siblings(not necessarily immediate sibling) of the first element and belong to same parent.

span ~ p{
  color:yellow;
}
Enter fullscreen mode Exit fullscreen mode

After applying the above combination, all the adjacent paragraphs following span tag will have text colored yellow. Notice that paragraph four is not selected since it does not belongs to the same parent.

Alt Text

QUIZ TIME

.container p[class*="para-four"]{
  color: black;
  background-color: white;
}
Enter fullscreen mode Exit fullscreen mode

What do you think the above selector combination will display and why?🤔
Let's hear out in comments!

For more details about selectors checkout MDN site

Top comments (0)