Skip to content Skip to sidebar Skip to footer

Why Doesn't Nth-of-type Work On An Image Wrapped In An A Tag?

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. Here

Solution 1:

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

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).

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.

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 Fiddle demo.

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.

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>.

References:


Post a Comment for "Why Doesn't Nth-of-type Work On An Image Wrapped In An A Tag?"