CSS Combinators

A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.A combinator is something that explains the relationship between the selectors.

There are four different combinators in CSS3:

  • descendant selector
  • child selector
  • adjacent sibling selector
  • general sibling selector

Adding a class or ID isn’t the only way to style some parts of your document differently. Our more complex selectors give you ways to select elements based on where they are in the document. The first set of selectors we can look at are the Combinators. There are four different Combinators and they work by combining other selectors.

Descendant Selector

Example -

Child Selector

The child selector selects all elements that are the immediate children of a specified element.Select all elements that are immediate children of a specified parent.The descendant selector will target all children, even if there are other elements in-between the parent and child. For example if we take the following markup:

The following example selects all <p> elements that are immediate children of a <div> element:

Adjacent Sibling Selector

The adjacent sibling selector is a useful selector that enables the selection of an element when it is next to another element. This is how we can deal with things like stacked headings in CSS.

A common request is to make the paragraph that comes directly after a heading different in some way, to make it stand out.The adjacent sibling selector selects all elements that are the adjacent siblings of a specified element.Sibling elements must have the same parent element, and "adjacent" means "immediately following".