gpt4 book ai didi

CSS nth-of-type 不合逻辑

转载 作者:行者123 更新时间:2023-11-28 09:27:10 26 4
gpt4 key购买 nike

CSS:

.banner:nth-of-type(1) {background-color:red;}
.banner:nth-of-type(2) {background-color:blue;}

HTML:

<div id="container">
<div class="copy">copy 1</div>
<div class="banner">banner 1</div>
<div class="copy">copy 1</div>
<div class="banner">banner 2</div>
<div class="copy">copy 1</div>
<div class="banner">banner 3</div>
<div class="banner">banner 4</div>
</div>

CSS 不应该计算 .banner 元素而不考虑其他同级元素吗?

我希望横幅 1 有红色背景,横幅 2 有蓝色背景,但得到的横幅 1 有蓝色背景,而横幅 2 没有背景——如果我使用 ,我会期望这样第 n 个 child (n)。在这里检查我的 fiddle :http://jsfiddle.net/JjNBV/3/

最佳答案

nth-of-type适用于元素的类型——即 <div>在这种情况下,不上课。

  • .banner:nth-of-type(1)不匹配任何内容,因为 .banner 都不匹配元素是第一个divcontainer里面.

  • .banner:nth-of-type(2)匹配第一个 .banner元素,因为它是第二个 divcontainer里面.

没有以您期望的方式匹配类的 CSS3 选择器。

如果您想要这种行为,您需要为您的横幅和文案使用不同的元素类型,然后 nth-of-type会随心所欲地为你工作。 HTML5 提供了几个元素,可以满足您在这方面的需求。

您使用哪些元素取决于您使用它们的目的;你提供的代码没有提供足够的线索让我给你一个明确的建议,但这是你的代码与 copy元素从 <div> 更改进入<article>元素...

<div id="container">
<article class="copy">copy 1</article>
<div class="banner">banner 1</div>
<article class="copy">copy 1</article>
<div class="banner">banner 2</div>
<article class="copy">copy 1</article>
<div class="banner">banner 3</div>
<div class="banner">banner 4</div>
</div>

通过此更改,您现有的 CSS 现在应该可以按预期工作。 (和 here is the jsFiddle 以显示其正常工作)

CSS4 确实有一个选择器 nth-match() 这也可能会满足您的需求,但没有浏览器支持此选择器(在不久的将来也不会支持),因此目前这不是一个真正的选择。

关于CSS nth-of-type 不合逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21190867/

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