6

I'm attempting to resize images in a row with CSS, based on how many images are in the same row. For example, if there are four img elements in the same p, they are styled a certain way. Here is the working code, based on this answer:

HTML:

<p>
  <img src="preview.png">
  <img src="preview.png">
  <img src="preview.png">
  <img src="preview.png">
</p>

CSS:

.post-content p img:first-child:nth-last-child(4),
.post-content p img:first-child:nth-last-child(4) ~ img {
    width: 25%; /* fallback for browsers that don't support calc */
    width: calc((100% / 4) - 0.8%);
    margin-left: calc(1%);
}

.post-content p img:first-child:nth-last-child(4) { /* First image in group of four */
    margin-left: 0;
}

The result looks like this:

enter image description here

However, this does not work for images wrapped in a tags, but with the rest of the formatting identical, like this:

<p>
  <a href="#"><img src="preview.png"></a>
  <a href="#"><img src="preview.png"></a>
  <a href="#"><img src="preview.png"></a>
  <a href="#"><img src="preview.png"></a>
</p>

I am unable to find a solution in this case. Any help would be much appreciated.

BoltClock
  • 665,005
  • 155
  • 1,345
  • 1,328
user2255592
  • 147
  • 1
  • 10

2 Answers2

4

The :nth-child()'s, :first-child's, and sibling selector need to be based off of the a tags, since those are the children and siblings, then the selectors should end with img to target the CSS property of the image.

p a:first-child:nth-last-child(4) img,
p a:first-child:nth-last-child(4) ~ a img {
    width: 25%;
    width: calc((100% / 4) - 0.8%);
    margin-left: calc(1%);
}

p a:first-child:nth-last-child(4) img {
    margin-left: 0;
}
<p>
  <a href="#"><img src="http://kenwheeler.github.io/slick/img/fonz1.png"></a><a href="#"><img src="http://kenwheeler.github.io/slick/img/fonz1.png"></a><a href="#"><img src="http://kenwheeler.github.io/slick/img/fonz1.png"></a><a href="#"><img src="http://kenwheeler.github.io/slick/img/fonz1.png"></a>
</p>
Michael Coker
  • 50,703
  • 5
  • 56
  • 56
0

Have you tried replacing the img with an a before first-child in your CSS? That is,

.post-content p a:first-child:nth-last-child(4) img,
.post-content p a:first-child:nth-last-child(4) ~ a img {
    width: 25%;
    width: calc((100% / 4) - 0.8%);
    margin-left: calc(1%);
}

.post-content p a:first-child:nth-last-child(4) img {
    margin-left: 0;
}
wogsland
  • 8,299
  • 18
  • 54
  • 83