为什么 nth-of-type 不能处理包含在 a 标签中的图像?

Ant*_*y_Z 1 html css css-selectors

我正在尝试使用 nth-of-type 函数对一系列中的特定图像进行样式设置,但当我将图像包装在 a 标签中时,它似乎会中断。如果我只使用图像,效果很好。

这是我的小提琴: http://jsfiddle.net/o87oyfrx/1/

.row2 img:nth-child(2) {
    border: 1px solid green;
} 

<div class="row2">
    <a href="http://abcnews.go.com/"><img src="http://abcnews.go.com/assets/images/navigation/abc-logo.png" /></a>
    <a href="http://abcnews.go.com/"><img src="http://abcnews.go.com/assets/images/navigation/abc-logo.png" /></a>
</div> 
Run Code Online (Sandbox Code Playgroud)

Dav*_*mas 5

:nth-of-type()为什么对包含在标签中的图像不起作用<a>

会的,但由于您使用的是:nth-child(), 而不是:nth-of-type(),我将改为解决这个问题(尽管无论如何,答案几乎相同)。

您面临的问题是您的选择器选择了错误的元素,因为<img>其中的元素.group3单独包装在<a>元素中,因此img:nth-child(2)无法匹配任何内容;如果您尝试过img:nth-child(1)、 或img:first-child,您会发现这两个<img>元素都已被成功选择,因为它们都:nth-child(1)位于:first-child各自的父元素内。

因此,要选择<img>中出现的第二个元素.group3,我们需要通过其父元素进行选择<a>

.row3 a:nth-child(2) img {
    border: 1px solid green;
}
Run Code Online (Sandbox Code Playgroud)

JS 小提琴演示

重要的是要注意,它:nth-child()所做的事情正是它告诉你它所做的事情(按照它的名字);如果它是其父元素,它会选择一个<img>元素。由于所有元素都单独包装在elements 中,因此这些元素都无法匹配。:nth-child()<img><a><img>

这意味着要选择第二个,<img>我们需要选择唯一的图像(或可能是所有图像),该图像保存在元素的实际第二个子元素中.row3,即<a>.

参考: