CSS adjacent sibling combinator
Created By: chatGPT
CSS Adjacent Sibling Combinator is a powerful tool that helps style elements based on their relationship in the document tree. It selects an element that is directly adjacent to a specified element. The syntax for this combinator is as follows:
A + B {
/* styles for B that is adjacent to A */
}
Here, A is the first element, and B is the adjacent sibling that comes right after A. This combinator helps ensure that styles are applied only when B immediately follows A in the markup.
h2 + p {
color: blue;
}
In the example above, the paragraph (
<p>
) will be colored blue only if it directly follows an <h2>
. If there is any other element between the <h2>
and <p>
, the style will not apply.<h2>Title</h2>
<p>This paragraph will be blue if it follows an h2 directly.</p>
<div>Separator</div>
<p>This won't be blue.</p>
This combinator can be beneficial in various scenarios, such as applying styles to the first element in a group of elements or customizing layouts based on the order of elements.
ul li + li {
margin-top: 10px;
}
In this case, adding a 10px margin to every
<li>
that directly follows another <li>
within a list helps create a cleaner look, enhancing readability.<ul>
<li>First item</li>
<li>Second item</li>
</ul>