之前,我有这个工作:
CSS
.categorie-image:not(:first-of-type):not(:nth-of-type(2)):not(:nth-of-type(3)) {
margin-top: 20px;
}
HTML
<div class="categorie-image custom-border" style="background-image:url(succes.png);">
<div class="categorie-title">Text</div>
</div>
但后来我需要让 div 可点击,所以我将它们包裹在 <a href="#">
中:
<a href="#">
<div class="categorie-image custom-border" style="background-image:url(succes.png);">
<div class="categorie-title">Text</div>
</div>
</a>
但是现在我的 CSS 不再工作了。我知道它与子元素有关,但我试过了:
-
a.categorie-image:not(:first-of-type)...
-
a > .categorie-image:not(:first-of-type)...
-
div.categorie-image:not(:first-of-type)...
但运气不好。我应该如何更改我的 CSS?
最佳答案
下面的选择器不再起作用,因为 div
其中有 class='categorie-image'
是该父类中的第一个类型(即 a
)。因此,否定 (:not(:first-of-type)
) 将阻止元素被选中。
.categorie-image:not(:first-of-type):not(:nth-of-type(2)):not(:nth-of-type(3)){
margin-top: 20px;
}
<a href="#">
<div class="categorie-image custom-border" style="background-image:url(succes.png);">
<div class="categorie-title">Text</div>
</div>
</a>
请注意,即使您已将否定附加到类选择器,nth-of-type
选择器实际上作用于元素类型。因此,您的选择器将选择每种类型(div
、a
、p
等)的第一个元素,这些元素不是每个父元素中其类型的第一个、第二个或第三个,并且< strong>还有类.categorie-image
.
另外,作为 Vitorino fernandes指出in his comment , 最好避免链接否定选择器并使用 nth-of-type(n+4)
(或 nth-child(n+4)
以适合您的情况为准)选择第三个之后的所有元素。
虽然以上是选择器不再起作用的原因,但我只能假设在 a
之前被添加你有一些其他div
div
之前的元素与 class='categorie-image'
.
关于html - 具有 nth-of-type 的 CSS 选择器在 <a> 标签内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33563063/