Combinators

A combinator  explains the relationship between the selectors.
CSS selectors are used to select the elements for style purpose.

A CSS selector can be a simple selector or a complex selector consisting of more than one selector and connected using combinators

There are four different combinators in CSS:

Sr. NO Types Description
1 child selector (>) The child selector selects all elements that are the children of a specified element.
2 general sibling selector (~) The general sibling selector selects all elements that are siblings of a specified element.
3 descendant selector (space) The descendant selector matches all elements that are descendants of a specified element.
4 adjacent sibling selector (+) The adjacent sibling selector is used to select an element that is directly after another specific element.

1. Child Selector (>)

This selector is used to select the element that is the immediate child of the specified tag. This combinator is stricter than the descendant selector because it selects only the second selector if it has the first selector element as its parent.

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

2. General Sibling Selector (~)

The general sibling selector is used to select the element that follows the first selector element and also share the same parent as the first selector element.

This can be used to select a group of elements that share the same parent element.

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

3. Descendant Selector (space)

This selector is used to select all the child elements of the specified tag. The tags can be the direct child of the specified tag or can be very deep in the specified tag.

The following example selects all p elements inside div elements:

4. Adjacent Sibling selector (+)

The Adjacent sibling selector is used to select the element that is adjacent or the element that is next to the specified selector tag.

The following example selects the first p element that are placed immediately after the div elements:

Exercise 14.1

This webpage describes Genghis Khan, an emperor who had many descendants, and includes a table with just a few of the emperors that descended from him.
Add a rule that targets only the elements that have the ’emperor’ class and are in the table. The rule should change the background color of those table cells.