Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the neighbor Selector of CSS

Shulou Source: shulou.com Published: 2022-06-01 06:27:56 10月03日 Update

This article introduces the knowledge of "how to use CSS's neighboring brother selector". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The neighboring sibling selector (Adjacentsiblingselector) selects the element immediately after another element, and both have the same parent element.

Select neighboring brothers (recommended: CSS tutorial)

If you need to select an element immediately after another element, and the two have the same parent element, you can use the adjacent sibling selector (Adjacentsiblingselector).

For example, if you want to increase the top margin of a paragraph that appears immediately after the H2 element, you can write:

H _ 2roomp {margin-top:50px;}

Thisisaheading.

Thisisparagraph.

Thisisparagraph.

Thisisparagraph.

Thisisparagraph.

Thisisparagraph.

The selector reads: "Select the paragraph that appears immediately after the H2 element. H2 and p elements have a common parent element."

Grammatical explanation:

The neighboring sibling selector uses the plus sign (+), which is the neighboring sibling combinator (Adjacentsiblingcombinator).

Note: like the child combinator, there can be a blank character next to the neighboring sibling combinator.

Take a look at the following document tree fragment:

Listitem1

Listitem2

Listitem3

Listitem1

Listitem2

Listitem3

In the above snippet, the div element contains two lists: an unordered list and an ordered list, each containing three list items. The two lists are neighboring brothers, and the list items themselves are neighboring brothers.

However, the list items in the first list and the list items in the second list are not adjacent brothers, because the two sets of list items do not belong to the same parent element (cousins at most).

Keep in mind that you can only select the second element of two neighboring brothers with a combination. Look at the selector below:

Li+li {font-weight:bold;}

The above selector only changes the second and third list items in the list to bold. The first list item is not affected.

This is the end of the content of "how to use CSS's neighbor Selector". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Select elements brothers two same three content more paragraphs fragments knowledge please see face learning practical orderly learning next above plus sign Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Tech Info Xiaomi Shulou Information macOS