gpt4 book ai didi

css - 选择器 div + p(加号)和 div ~ p(波浪号)之间的区别

转载 作者:数据小太阳 更新时间:2023-10-29 09:08:08 24 4
gpt4 key购买 nike

w3schools的方式短语吧,它们听起来一样。

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

如果 <p>元素紧跟在 <div> 之后元素,这是否意味着 <p>元素前面有一个 <div>元素?

无论如何,我正在寻找一个选择器,我可以在其中选择一个紧接在给定元素之前的元素。

最佳答案

相邻兄弟选择器 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>

通用兄弟选择器 X ~ Y

The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.

ul ~ p {
color: red;
}

This sibling combinator is similar to X + Y, however, it's less strict. While an adjacent selector (ul + p) will only select the first element that is immediately preceded by the former selector, this one is more generalized. It will select, referring to our example above, any p elements, as long as they follow a ul.

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

来源

code.tutsplus

General sibling selectors MDN

Adjacent sibling selectors w3

关于css - 选择器 div + p(加号)和 div ~ p(波浪号)之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26282375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com