CSS Combinators

CSS Combinators

 

CSS Combinators

A combinator is something that explains the relationship between the selectors.

A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.

There are four different combinators in CSS:

  • descendant selector (space)
  • child selector (>)
  • adjacent sibling selector (+)
  • general sibling selector (~)

Descendant Selector

The descendant selector matches all elements that are descendants of a specified element.

The following example selects all

elements inside

elements: 

 

Example

div p {
  background-color: yellow;
}

Child Selector (>)

The child selector selects all elements that are the children of a specified element.

The following example selects all

elements that are children of a

element:

 

Example

div > p {
  background-color: yellow;
}


Adjacent Sibling Selector (+)

The adjacent sibling selector is 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".

The following example selects the first

element that are placed immediately after

elements:

 

Example

div + p {
  background-color: yellow;
}

General Sibling Selector (~)

The general sibling selector selects all elements that are next siblings of a specified element.

The following example selects all

elements that are next siblings of

elements: 

 

Example

div ~ p {
  background-color: yellow;
}

Test Yourself With Exercises

Exercise:

Change the color of all

elements, that are descendants of

elements, to "red".
 

 


All CSS Combinator Selectors

Selector Example Example description
  div p Selects all

elements inside

elements
  div > p Selects all

elements where the parent is a

element
  div + p Selects the first

element that are placed immediately after

elements
  p ~ ul Selects every
  • element that are preceded by a

element


 
CSS Combinators

Login
ADS CODE