user2255592
user2255592

Reputation: 167

Applying styles to the child of an adjacent sibling

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.

Upvotes: 6

Views: 54

Answers (2)

wogsland
wogsland

Reputation: 9508

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;
}

Upvotes: 0

Michael Coker
Michael Coker

Reputation: 53674

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>

Upvotes: 4

Related Questions