CSS Adjacent Selector with Example
In this article, we will see about CSS adjacent selector example.
What are adjacent siblings?
<header>
<h2>text here</h2>
<p>text here </p>
<a>text here</a>
<header>
Two or more nodes having the same parent are known as siblings. In the above code, <h2>, <p> and <a> element have same parent known as <header>, hence <h2>, <p> and <a> element are considered as siblings. Here, <h2> and <p> are adjacent siblings and <p> and <a> are adjacent siblings.
Adjacent siblings are one element beside another in the same header element. Whereas <h2> and <a> elements are not considered as adjacent siblings because they are not one beside another in the middle we have a <p> element, but you can consider <h2>, <p> and <a> elements as adjacent siblings.
Adjacent Sibling (+) Selector
An adjacent sibling is also known as the Next sibling selector. It selects any HTML element targeted by the selector written after the (+) character, which is a sibling of an immediately preceded by any HTML element targeted by the selector written before the (+) character.
Syntax of adjacent sibling (+) selector:
selector1 + selector2
{
declaration list;
}
Here, we have selects the element selector1 + selector2 in the flower bracket we write the declaration list. It selects any HTML element targeted by the selector2, which is a sibling of any immediately preceded by any HTML element targeted by the selector1.
Example
CSS:
h2 + p
{
border : 2px solid red;
}
HTML:
<header>
<h2>Heading Text</h2>
<p>Paragraph Text</p>
<a href="#">Anchor Text</a>
<header>
Output:
In the above code, we have an <h2> and <p> element. In CSS, we select h2 + p using the adjacent selector and in flower brackets, we wrote a 2px solid red border. It selects any <p> element which is a sibling of an immediately preceded by any h2 element.
We are telling the browser, to check whether <h2> and <p> are siblings, here both are siblings. Then we check the <p> element is immediately preceded by the <h2> , here yes of course <p> element is immediately preceded by the <h2>. Hence, we set the border to the <p> element only, So see the given output the border is displayed for paragraph text only.
So if you style in CSS using adjacent sibling selector, first it will check the given elements are siblings and adjacent siblings then it will apply style only to the last element.