Home >Web Front-end >CSS Tutorial >When to use CSS adjacent sibling selector

When to use CSS adjacent sibling selector

(*-*)浩
(*-*)浩Original
2019-12-30 16:16:433182browse

When to use CSS adjacent sibling selector

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn