为什么nth-of-type无法处理包裹在标签中的图像? [英] Why doesn't nth-of-type work on an image wrapped in an a tag?

查看:101
本文介绍了为什么nth-of-type无法处理包裹在标签中的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting to style a specific image in a series using the nth-of-type function but it seems to break when I wrap images in an a tag. If I only use images it works fine.

这是我的小提琴: 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> 

推荐答案

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

Why doesn't :nth-of-type() work on an image wrapped in an <a> tag?

可以,但是由于您使用的是:nth-child(),而不是:nth-of-type(),因此我会解决(尽管答案几乎是相同的,无论如何).

It would, but since you're using :nth-child(), and not :nth-of-type(), I'll address that instead (though the answer is pretty much the same, regardless).

您面临的问题是选择器选择了错误的元素,因为.group3中的<img>元素分别包装在<a>元素中,因此img:nth-child(2)不能匹配任何内容.您是否尝试过 img:nth-child(1)

The problem you're facing is that your selector is selecting the wrong element, because the <img> elements within .group3 are individually wrapped in <a> elements, so img:nth-child(2) can't match anything; had you tried img:nth-child(1), or img:first-child, you'd see that both <img> elements would have been successfully selected because they're both :nth-child(1) and :first-child within their respective parents.

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

So, to select the second <img> element that appears within .group3, we need to select via its parent, the <a>:

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

JS小提琴演示.

请务必注意,:nth-child()确实准确地完成了 的操作(以它的名义);它选择<img>元素 if 是其父元素的:nth-child().由于所有<img>元素都单独包装在<a>元素中,因此这些<img>元素都无法匹配.

It's important to note that :nth-child() does precisely what it tells you it does (in its very name); it selects an <img> element if it is the :nth-child() of its parent. As all the <img> elements are individually wrapped in <a> elements, none of those <img> elements can be matched.

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

That means to select the second <img> we need to select the only image (or potentially all the images), that are held within the actual second-child of the .row3 element, which is the <a>.

参考文献:

这篇关于为什么nth-of-type无法处理包裹在标签中的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆