我正在尝试使用 nth-of-type 函数为系列中的特定图像设置样式,但当我将图像包装在 a 标签中时它似乎会中断。如果我只使用图片,效果很好。
这是我的 fiddle : 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>
最佳答案
Why doesn't
:nth-of-type()
work on an image wrapped in an<a>
tag?
会的,但是因为你使用的是 :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
在他们各自的 parent 中。
所以,选择第二个<img>
.group3
中出现的元素,我们需要通过其父级选择 <a>
:
.row3 a:nth-child(2) img {
border: 1px solid green;
}
重要的是要注意 :nth-child()
精确地它告诉你它做了什么(以它的名字);它选择一个 <img>
元素 if 它是 :nth-child()
它的 parent 。由于所有 <img>
元素单独包装在 <a>
中元素,这些都不是<img>
可以匹配元素。
这意味着选择第二个<img>
我们需要选择唯一的图像(或可能是所有图像),这些图像保存在 .row3
的实际第二个 child 中。元素,即 <a>
.
引用资料:
- >
:nth-child()
.
关于html - 为什么 nth-of-type 不适用于包含在 a 标签中的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26897913/