html - 具有 nth-of-type 的 CSS 选择器在 <a> 标签内不起作用

标签 html css css-selectors

之前,我有这个工作:

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选择器实际上作用于元素类型。因此,您的选择器将选择每种类型(divap 等)的第一个元素,这些元素不是每个父元素中其类型的第一个、第二个或第三个,并且< 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/

相关文章:

html - 选择器后更改 n 项的样式

html - 为什么Bootstrap导航栏底部的阴影在开始和结束时被切断

html - 整页背景 Bootstrap 和超链接

html - Bootstrap 中的中心表单

隐藏文本节点但不隐藏其他子元素的 CSS 选择器

javascript - 如何在ReactJS中单击时旋转伪元素,其内容是SVG

javascript - 鼠标悬停后更改 YouTube 播放器大小的最佳方法是什么?

javascript - MSIE 让我的 Slidejs 代码看起来很糟糕

html - Divs 不会保留内联 chrome 扩展

javascript - 维护缩小文件和部署/开发的最佳实践