Reputation: 231
I have a grid of images that can contain up to 10 images per row. I want to apply unique dimensions for all images based on how many are contained within a row.
How can I determine the number of images per row with a CSS selector?
<div>
<img src="http://lorempixel.com/50/50" />
</div>
<div>
<img src="http://lorempixel.com/50/50" />
<img src="http://lorempixel.com/50/50" />
</div>
<div>
<img src="http://lorempixel.com/50/50" />
<img src="http://lorempixel.com/50/50" />
<img src="http://lorempixel.com/50/50" />
</div>
... etc
Upvotes: 2
Views: 700
Reputation: 231
By combining :nth-child()
, :nth-last-child()
and the ~
combinator you can accomplish this.
You need two selectors. The first one will select the first image, only if it's also the last child of whatever number is specified in the argument of :nth-last-child()
. To select the rest of the images that follow, you add on ~
to the selector (which targets all images that follow the first image that satisfy the above condition).
So if I wanted to target images when there is 3 per row, I would use:
div img:nth-child(1):nth-last-child(3),
div img:nth-child(1):nth-last-child(3) ~ img {
border-radius: 50%;
}
Fiddle: http://jsfiddle.net/vp1Ljm3o/
Upvotes: 4