The Adjacent sibling selector can select an element immediately after another element, and both have the same parent element .
Select adjacent brothers # If both have the same parent element, you can use the Adjacent sibling selector.
For example, if you want to increase the top margin of the paragraph that appears immediately after the h1 element, you can write:<!DOCTYPE HTML> <html> <head> <style type="text/css"> h1 + p {margin-top:50px;} </style> </head> <body> <h1>This is a heading.</h1> <p>This is paragraph.</p> <p>This is paragraph.</p> <p>This is paragraph.</p> <p>This is paragraph.</p> <p>This is paragraph.</p> </body> </html>
This selector reads: "Select immediately after A paragraph that appears after an h1 element. The h1 and p elements have a common parent element."
Grammar explanation:The adjacent sibling selector uses the plus sign ( ), which is the adjacent sibling combinator.
Note:Like sub-combination symbols, there can be blank characters next to adjacent sibling combination symbols.
Please look at the following document tree fragment:
<div> <ul> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ul> <ol> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ol> </div>
In the above fragment, the div element contains two lists: an unordered list and an ordered list , each list contains three list items. The two lists are adjacent siblings, as are the list items themselves. However, the list items in the first list and the list items in the second list are not adjacent siblings, because the two sets of list items do not belong to the same parent element (they can only be considered cousins at most).
Remember that only the second element of two adjacent siblings can be selected with a combiner. Take a look at the following selector:li + li {font-weight:bold;}
The above selector will only make the second and third list items in the list bold. The first list item is not affected.
The above is the detailed content of When to use CSS adjacent sibling selector. For more information, please follow other related articles on the PHP Chinese website!