gpt4 book ai didi

html - 仅选择 div 中的第一个和最后一个链接

转载 作者:搜寻专家 更新时间:2023-10-31 22:00:22 25 4
gpt4 key购买 nike

我的结构如下:

<div class="navigation_sub_item_background" id="sub_nav_2">
<div class="navigation_sub_item" id="2_1">
<a class="navigation__sub__link" href="?p=2_1">
<span>
Test 3
</span>
</a>
</div>
<div class="navigation_sub_item" id="2_2">
<a class="navigation__sub__link" href="?p=2_2">
<span>
Test 4
</span>
</a>
</div>
<div class="navigation_sub_item" id="2_3">
<a class="navigation__sub__link" href="?p=2_3">
<span>
Test 5
</span>
</a>
</div>
<div class="navigation_sub_item" id="2_4">
<a class="navigation__sub__link" href="?p=2_4">
<span>
Test 6
</span>
</a>
</div>
</div>

我只想选择第一个链接和最后一个链接。我尝试了 div.navigation_sub_item > a.navigation__sub__link:first-of-type 但这会选择所有链接。

有什么建议吗?

最佳答案

选择第一个和最后一个链接

由于您的链接包含在 div 元素中,您需要选择第一个和最后一个 div 并定位第一个或最后一个 a其中的元素:

.navigation_sub_item:first-child a:first-of-type {
/* The very first link. */
}

.navigation_sub_item:last-child a:last-of-type {
/* The very last link. */
}

请注意,我已经在 a 元素上指定了 first-of-typelast-of-type 以防万一div 元素中存在多个 a 元素。如果您不关心它们之前或之后的其他元素,您可能希望将它们替换为 first-childlast-child


只有一个元素存在的特殊情况

I want them all, thats cool. But what should I do if there is only one .navigation__sub__link-element? then the :last-child rule will be applied but I want another rule to be used.

在这种情况下,您可以通过指定 both first-childlast-child 来覆盖这些选择器的特异性:

.navigation_sub_item:first-child:last-child a {
/* This will override the above selectors. */
}

或者,如果您没有在 a 元素上指定 :first-of-type:last-of-type,您同样可以使用 :only-child 选择器:

.navigation_sub_item:only-child a {
/* This will also override the above selectors. */
}

关于html - 仅选择 div 中的第一个和最后一个链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31403154/

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