CSS Combinator Selectors

CSS Combinator Selectors

CSS combinator selectors enable you to target web elements based on their relationships to other elements within the HTML structure. The main types of combinator selectors are:

1. Descendant Selector

The descendant selector targets elements that are nested within a specified parent element, no matter how deep the nesting. The syntax is parent child. For example:

<!DOCTYPE html>
<html>
  <body>
    <div class="container">
      <p>This is my first paragraph.</p>
      <div>
        <p>This is my second paragraph.</p>
      </div>
    </div>
  </body>
</html>
HTML code preview

In this example, the .container p selector will target both paragraph (<p>) elements inside the .container div, including the nested one.

The target element is outlined with blue box.

2. Child Selector

The child selector targets only the direct (immediate) children of a specified parent element. It does not include nested descendants. The syntax is parent > child. For example:

<!DOCTYPE html>
<html>
  <body>
    <div class="container">
      <p>This is my first paragraph.</p>
      <div>
        <p>This is my second paragraph.</p>
      </div>
    </div>
  </body>
</html>
HTML code preview

Here, the .container > p selector will only target the first paragraph (<p>) because it is a direct child of the .container div.

The target element is outlined with blue box.

3. Adjacent Sibling Selector

The adjacent sibling selector targets the element immediately following a specific element, provided both share the same parent. The syntax is sibling1 + sibling2. For example:

<!DOCTYPE html>
<html>
  <body>
    <h1>This is my heading.</h1>
    <p>This is my first paragraph.</p>
    <p>This is my second paragraph.</p>
  </body>
</html>
HTML code preview

In this case, the h1 + p selector will target only the first paragraph (<p>) directly following the heading (<h1>), ignoring the second paragraph.

The target element is outlined with blue box.

4. General Sibling Selector

The general sibling selector targets all sibling elements that follow a specified element and share the same parent. Unlike the adjacent sibling selector, it applies to all matching siblings. The syntax is sibling1 ~ sibling2. For example:

<!DOCTYPE html>
<html>
  <body>
    <h1>This is my heading.</h1>
    <p>This is my first paragraph.</p>
    <p>This is my second paragraph.</p>
  </body>
</html>
HTML code preview

Here, the h1 ~ p selector will select both paragraph (<p>) elements that follow the heading (<h1>).

The target element are outlined with blue boxes.