CSS interview question

What are Combinators in CSS?

Answer

A combinator is the character in a selector that connects two selectors together. There are four types of combinators.

a) Descendant Combinator (space): The descendant selector matches all elements that are descendants of a specified element.

The following example selects all <p> elements inside <div> elements:

div p {
  background-color: yellow;
}

b) Child Combinator (>): The child selector selects all elements that are the children of a specified element.

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

div > p {
  background-color: yellow;
}

c) Adjacent Sibling Combinator (+): The adjacent sibling selector selects all elements that are the adjacent siblings of a specified element.

The following example selects all <p> elements that are placed immediately after <div> elements:

div + p {
  background-color: yellow;
}

 

d) General Sibling Combinator (~): The general sibling selector selects all elements that are siblings of a specified element.

The following example selects all <p> elements that are siblings of <div> elements:

div ~ p {
  background-color: yellow;
}

More Technical Interview Topics