loading

CSS Combinators

Something that clarifies the connection between the selectors is called a combinator.

Multiple basic selectors can be contained within a CSS selection. In between the basic selectors, a combinator can be used.

In CSS, there are four distinct combinators:

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

Descendant Selector

All elements that are descendants of a given element are matched by the descendant selector.

All <p> elements inside <div> components are selected in the example below:

Example

				
					div p {
  background-color: yellow;
}
				
			

Child Selector (>)

All items that are offspring of a given element are chosen by the child selector.

The example that follows chooses every <p> element that is a child of a <div> element:

Example

				
					div > p {
  background-color: yellow;
}
				
			

Adjacent Sibling Selector (+)

To choose an element that comes right after another particular element, use the nearby sibling selector.

Parent elements must be the same for sibling elements, and “adjacent” refers to “immediately following”.

The <p> element that comes just after the <div> elements is chosen in the example below:

Example

				
					div + p {
  background-color: yellow;
}
				
			

General Sibling Selector (~)

All elements that are the next siblings of a given element are chosen using the generic sibling selector.

The example that follows picks all <p> elements that are <div> elements’ next siblings:

Example

				
					div ~ p {
  background-color: yellow;
}
				
			

All CSS Combinator Selectors

Selector Example Example description
element element div p Selects all <p> elements inside <div> elements
element>element div > p Selects all <p> elements where the parent is a <div> element
element+element div + p Selects the first <p> element that are placed immediately after <div> elements
element1~element2 p ~ ul Selects every <ul> element that are preceded by a <p> element
Share this Doc

CSS Combinators

Or copy link

Explore Topic