CSS Combinators (CSS advanced selectors)

CSS Combinators join several different selectors into new and more capable of targeting a portion of the document.

There are 4 types of combinators

css advanced selectors

1. Descendant selector

Descendant selector in CSS which matches all child elements that are descendants of the parent element. Descendant selector including elements that are not only direct descendants. These element may be a child, grandchild, great grandchild, and so on.

A descendant selector is made up of two or more selectors separated by white space.

The above code tells the browser to select all em elements that are descendants of p elements to apply the rule. The other em elements in the page will not be selected by this rule.

It is also possible to nest descendant selectors in several layers deep.

HTML Source

output

descendant selectors

2. Child Selector (CSS Direct Child Selector)

A child selector is similar to a descendant selector, but it targets only the direct children of a given element. That means it matches all elements that are the immediate children of a specified element. The special character used in child selector is the > (greater than) sign.

Read right to left, the selector p > em translates as, selects any em element that is an immediate child of a p element.

output

child selector

3. Adjacent Sibling Selector (CSS Next Sibling Selector)

The Adjacent Sibling Selector selects an element`s next sibling, that is it allows you to select an element that is directly after another specific element. The special character used in Adjacent Sibling selector is the + (plus) character.

Above CSS code states that all paragraph elements that are directly after a < div > is #FF0066 color.

output

adjacent sibling selector

General Sibling Selectors

The general sibling selector in CSS is almost similar to the adjacent sibling selector. The difference is that it select any element that follows another element , it does not need to be the directly preceding element, can appear anywhere after it. The special character used in Adjacent Sibling selector is the ~ (tilde) character.

Above code states that all h1 elements that are anywhere after < p > is #FF0066 color.

output

general sibling selectors

From the above image, you can understand how the General Sibling Selectors styles the HTML document.