How to style every element that have adjacent item right before it ?
You can easily style every element which has an adjacent item right before it using the Adjacent Sibling Selector (+). The adjacent sibling selector is used to select the element that is adjacent or the element that is next to the specified selector tag. This combinator selects only one tag that is just next to the specified tag.
Note: Selectors are used for selecting the HTML elements in the attributes and adjacent sibling selector (+) is one type of selector. The syntax is straightforward, just two or more selectors separated by a plus (+) symbol.
Prerequisite: Good understanding of combinator
Syntax:
former_element + target_element { style properties }
Example 1: The adjacent sibling selector will only select sibling elements directly following after another sibling element. Both elements share the same parent ( center ).
HTML
<!DOCTYPE html> < html > < head > < style > h1 { color: green; } /* styling the paragraph just after image tag p elements directly following after img elements will be selected Both share same parent */ img + p { color: red; } img + p + p { color: green; } </ style > </ head > < body > < center > < h1 >GeeksforGeeks</ h1 > < img src = alt = "GeeksforGeeks logo" /> < p >I'm 1st paragraph after Image</ p > < p >I'm 2nd paragraph after Image</ p > < p >I'm 3rd paragraph after Image</ p > </ center > </ body > </ html > |
Output:
Example 2:
HTML
<!DOCTYPE html> < html > < head > < title >Combinator Property</ title > < style > h1 { color: green; } div+p { color: #009900; font-size: 32px; font-weight: bold; margin: 0px; text-align: center; } div { text-align: center; } p { text-align: center; } </ style > </ head > < body > < center > < h1 >Welcome to GeeksforGeeks</ h1 > < div >Adjacent sibling selector property</ div > < p >GeeksforGeeks</ p > < div > < div >child div content</ div > < p >G4G</ p > </ div > < p >Geeks</ p > < p >Hello</ p > </ center > </ body > </ html > |
Output:
Please Login to comment...