Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

css - Difference between the selectors div + p (plus) and div ~ p (tilde)

The way that w3schools phrases it, they sound the same.

W3Schools' CSS reference

div + p
Selects all <p> elements that are placed immediately after <div> elements

div ~ p
Selects every <p> element that are preceded by a <div> element

If a <p> element is immediately after a <div> element, doesn't that mean that the <p> element is preceded by a <div> element?

Anyhow, I'm looking for a selector where I can select an element that is place immediately before a given element.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Adjacent sibling selectors X + Y

Adjacent sibling selectors have the following syntax: E1 + E2, where E2 is the subject of the selector. The selector matches if E1 and E2 share the same parent in the document tree and E1 immediately precedes E2, ignoring non-element nodes (such as text nodes and comments).

ul + p {
   color: red;
}

In this example it will select only the element that is immediately preceded by the former element. In this case, only the first paragraph after each ul will have red text.

ul + p {
    color: red;
}
<div id="container">
    <ul>
        <li>List Item</li>
        <li>List Item</li>
        <li>List Item</li>
        <li>List Item</li>
    </ul>
    <p>This will be red</p>
    <p>This will be black</p>
    <p>This will be black</p>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...