Home >Web Front-end >CSS Tutorial >How Does the CSS Adjacent Sibling Combinator ( ) Work?
Understanding the CSS Adjacent Sibling Combinator:
In CSS, the symbol is known as the adjacent sibling combinator. It allows you to target specific HTML elements that are positioned adjacent to each other.
How Does the Combinator Work?
The combinator ensures that the targeted element (the second element in the selector) must follow the first element (the first element in the selector) immediately. There should be no other elements in between the two elements for the selector to match.
Example: h2 p
Consider the following CSS rule:
<code class="css">h2 + p { font-size: 1.4em; font-weight: bold; color: #777; }</code>
This rule targets all p elements that are adjacent to h2 elements. In other words, it will only affect p elements that appear immediately after h2 elements.
Illustration
Take this HTML code as an example:
<code class="html"><h2>Headline!</h2> <p>The first paragraph.</p> <!-- Selected --> <p>The second paragraph.</p> <!-- Not selected --> <h2>Another headline!</h2> <blockquote> <p>A quotation.</p> <!-- Not selected --> </blockquote></code>
Only the first p element will be selected by the h2 p selector because it is adjacent to an h2. The second p element is not selected because it is separated from the h2 by a
. The p element within the blockquote is also not selected because there is no h2 element immediately preceding it within the same block.Distinction from the General Sibling Combinator ~
Unlike the combinator, the general sibling combinator ~ does not require adjacent placement. It selects elements that are siblings, regardless of their position in relation to each other.
The above is the detailed content of How Does the CSS Adjacent Sibling Combinator ( ) Work?. For more information, please follow other related articles on the PHP Chinese website!