CSS

Last Updated: 10/5/2022

CSS Combinators/Relational Selectors

  • You can select elements based on relationship with other elements using Combinators
  • Four different combinators in CSS:
    • descendant selector (space)
    • child selector (>)
    • adjacent sibling selector (+)
    • general sibling selector (~)

Descendant Selector

  • Matches all elements that are descendants of a specified element.
div p {
  background-color: yellow;
}

Selects all <p> elements inside <div> elements:

Child Selector (>)

  • Selects all elements that are the direct children of a specified element.
div > p {  
background-color:  yellow;  
}

Selects all <p> elements that are direct children of a <div> element

Adjacent Sibling Selector (+)

  • Used to select an element that is directly after another specific element.
  • Sibling elements must have the same parent element, and "adjacent" means "immediately following".
div + p {
  background-color: yellow;
}

General Sibling Selector (~)

  • Selects all elements that are next siblings of a specified element.
div ~ p {
  background-color: yellow;
}