CSS Combinators

CSS Combinators

A selector can contain more than one simple selector. Between the simple selectors, we must include a combinator—something that explains the relationship between the selectors. There are three different combinators in CSS2, and one extra in CSS3.

There are four different combinators:

  1. descendant selector (space)
  2. child selector (>)
  3. adjacent sibling selector (+)
  4. general sibling selector (~)

1) descendant selector (space)

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

Example:

    <!DOCTYPE html>
<html>
<head>
<style>
div p {
    background-color: red;
}
</style>
</head>
<body>
<div>
  <p>Paragraph 1 in the div.</p>
  <p>Paragraph 2 in the div.</p>
  <span><p>Paragraph 3 in the div.</span></p>
</div>
<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>
</body>
</html>
Try it with the Editor

2) child selector (>)

This selector matches all elements that are the immediate children of a specified element.

Example:

    <!DOCTYPE html>
<html>
<head>
<style>
div > p {
    background-color: red;
}
</style>
</head>
<body>
<div>
  <p>Paragraph 1 in the div.</p>
  <p>Paragraph 2 in the div.</p>
  <span><p>Paragraph 3 in the div.</span></p>  //not Child but Descendant
</div>
<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>
</body>
</html>
Try it with the Editor

3) adjacent sibling selector (+)

A selector that uses the adjacent sibling combinator uses the plus symbol (+), and is almost the same as the general sibling selector. The difference is that the targeted element must be an immediate sibling, not just a general sibling.

Example:

    <!DOCTYPE html>
<html>
<head>
<style>
div + p {
    background-color: red;
}
</style>
</head>
<body>
<div>
  <p>Paragraph 1 in the div.</p>
  <p>Paragraph 2 in the div.</p>
</div>
<p>Paragraph 4. Not in a div.</p>
<p>Paragraph 5. Not in a div.</p>
</body>
</html>
Try it with the Editor

4) general sibling selector (~)

The general sibling selector is available in CSS3, and the combinator used in this selector is a tilde character (~).The selector matches elements that are siblings of a given element.

Example:

    <!DOCTYPE html>
<html>
<head>
<style>
div ~ p {
    background-color: yellow;
}
</style>
</head>
<body>
  <p>Paragraph 1.</p>
<div>  
  <code>Some code.</code>
  <p>Paragraph 2.</p>
</div>
<p>Paragraph 3.</p>
<code>Some code.</code>
<p>Paragraph 4.</p>
</body>
</html>
Try it with the Editor