Adjacent Sibling Selectors in CSS
CSS adjacent sibling selector or next sibling selector selects an element that is immediately after another element. It is used to select only those elements which immediately follow the first selector. Both elements should share the same parent.
Syntax
The syntax for CSS adjacent sibling selectors is as follows:
selector1 + selector2{/* property: value; */color: #04af2f }
Example of Adjacent Sibling Selectors
In this example, the style is applied only to the p element which is just after the div element. The other p elements remain unaffected.
<!DOCTYPE html><html lang="en"><head><style></style></head><body><p>div{ border: 2px solid #031926; } div + p { color: #04af2f; }
This paragraph is above the div and will not be green. </p><div><p> This paragraph is inside a div and will not be green.. </p></div><p> This paragraph 1 after the div and will be green.. </p><p>This paragraph 2 after the div and will not be green.. </p></body></html></pre>
Example 2
In this example, we have used an adjacent sibling selector to design the p element just after the h3 tag having the same parent element i.e. div container.
<!DOCTYPE html><html><head><style>.container { padding: 20px; border: 2px solid #031926; font-family: Verdana, sans-serif; } h3 + p { font-family: Verdana, sans-serif; font-size: 20px; font-style: italic; background-color: #04af2f; color: white; } </style></head><body><div class="container"><h3>This is an h3 tag</h3><p> This is a p tag that immediately follows the h3 tag. </p><p> This is another p tag, but it does not immediately after the h3 tag. </p></div><p>This is a p tag which is outside the parent div element.</p></body></html></pre>
Leave a Reply