gpt4 book ai didi

html - nth-of-type 无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-04 11:28:00 25 4
gpt4 key购买 nike

我有以下代码。

div img:nth-of-type(2n) {
float: left;
}

div img:nth-of-type(2n+1) {
float: right;
}
<div>
<p>Some random text.</p>
<p>
<img src="http://placehold.it/20x20">
</p>
<p>Some random text.</p>
<p>Some random text.</p>
<p>
<img src="http://placehold.it/20x20">
</p>
<p>Some random text.</p>
<p>
<img src="http://placehold.it/20x20">
</p>
<p>Some random text.</p>
</div>

我需要为偶数图像设置 float:left,为奇数图像设置 float:right。但在这两种情况下,都会触发第二个 css 规则。请帮助我。

最佳答案

您需要在 p 标签上使用 :nth-of-type 选择器。

这里的问题是段落元素是 div 的直接子元素。图像嵌套在段落标记内,而不是 div 的直接子级。所以它不会以 div 作为它的父级。


问题的 v1

div p:nth-of-type(2n) img { /* Select all even */
float: left;
}
div p:nth-of-type(2n+1) img { /* Select all odd */
float: right;
}
<div>
<p>...</p>
...
<p>
<img src="http://placehold.it/20x20">
</p>
...
<p>
<img src="http://placehold.it/20x20">
</p>
...
<p>
<img src="http://placehold.it/20x20">
</p>
...
</div>


问题的 v2

div p:nth-of-type(4n+2) img { /* Select 2,6,10 */
float: left;
}
div p:nth-of-type(4n) img { /* Select 4,8 */
float: right;
}
<div>
<p>Some random text.</p>
<p>
<img src="http://placehold.it/20x20" alt="1">
</p>
<p>Some random text.</p>
<p>
<img src="http://placehold.it/20x20" alt="2">
</p>
<p>Some random text.</p>
<p>
<img src="http://placehold.it/20x20" alt="3">
</p>
<p>Some random text.</p>
<p>
<img src="http://placehold.it/20x20" alt="1">
</p>
<p>Some random text.</p>
<p>
<img src="http://placehold.it/20x20" alt="2">
</p>
<p>Some random text.</p>
<p>
<img src="http://placehold.it/20x20" alt="3">
</p>
<p>Some random text.</p>
</div>

关于html - nth-of-type 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32232998/

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