Add margin-bottom to Image Before footer

I’m trying to see if there’s a way to add a margin-bottom to an img element only if it’s followed by a footer element. At the moment I’m using a special class (image-before-footer) on my last img element to acheive this, but was wondering if there’s a way to do it dynamically in CSS?

HTML

<div class="container">
  <h1>Title goes here</h1>
  <article>Lorem.</article>
  <img src="https://ununsplash.imgix.net/photo-1421284621639-884f4129b61d?dpr=1.80&fit=crop&fm=jpg&h=700&q=75&w=1050"/>
  <article>Lorem.</article>
  <img class="image-before-footer" src="https://ununsplash.imgix.net/photo-1421284621639-884f4129b61d?dpr=1.80&fit=crop&fm=jpg&h=700&q=75&w=1050"/>
  <footer class="footer">
    <p>Here are my footnotes</p>
  </footer>
</div>

CSS

article {
  margin: 3em 0;
}


img {
  width: 100%;
  vertical-align: middle;
  margin: 0;
}


.image-before-footer {
  margin-bottom: 3em;
}

Any help with this is appreciated. Thanks in advance!


solution

Since you can’t select previous sibling elements in CSS, why not just add a margin-top to the footer element if it follows an img element using the adjacent sibling combinator, +:

Example Here

img + footer {
  margin-top: 3em;
}

You could also just select the last img element using the :last-of-type pseudo class.

Of course, this assumes that the last img element will be succeeded by the footer, though.

Example Here

img:last-of-type {
  margin-bottom: 3em;
}