What is the adjacent sibling combinator in CSS?

The adjacent sibling combinator in CSS is a selector that allows you to target an element that is directly preceded by a specific element at the same hierarchy level in the DOM (Document Object Model) tree. The adjacent sibling combinator is represented by the plus sign (+).

The general syntax for using the adjacent sibling combinator is as follows:

selector1 + selector2 {
    /* styles */
}

Here, selector1 is the element that directly precedes selector2, and selector2 is the targeted element that will receive the styles defined within the curly braces {}.

For example, suppose you have the following HTML structure:

<div>
    <h2>Heading 2</h2>
    <p>Paragraph directly following Heading 2.</p>
    <p>Another paragraph following the first paragraph.</p>
</div>

If you wanted to style the first paragraph that comes immediately after any <h2> element, you could use the adjacent sibling combinator like this:

h2 + p {
    color: blue;
    font-weight: bold;
}

This CSS rule will apply the styles only to the first <p> element that directly follows an <h2> element. The second <p> will not be affected because it is not the adjacent sibling of the <h2>; it's the next sibling of the first <p>.

It's important to note that the adjacent sibling combinator only considers the very next sibling in the hierarchy. If there's another element in between, the combinator will not match the target element. For example, if there's a <div> between the <h2> and the <p>, the combinator will not match the <p> because it's not the immediate sibling of <h2>.

When using the adjacent sibling combinator, keep in mind the following:

  • The elements must have the same parent.
  • The second selector (selector2) is the one that gets styled.
  • The first selector (selector1) simply establishes the relationship that must be met for the styling to take effect on the second selector.

The adjacent sibling combinator is a powerful CSS tool for creating precise and context-dependent styles, and it can be particularly useful for styling elements based on their position in the markup without having to add extra classes or IDs.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon