Search code examples
cssflexbox

Images in a flexbox don't resize if I make them links


I have a flexbox of three square images, which I want to adjust to the size of the browser window as I narrow or widen it. I've managed to do this. However, I would like each image to be a link. When I try to do this, the images don't grow or shrink anymore.

This is the code where the images are not links, and the pictures resize as I want them to:

HTML:

<div class="container">

  <img src="001.jpg">
  <img src="002.jpg">
  <img src="003.jpg">

</div>

CSS:

.container {
  margin: auto;
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
}

.container img {
  overflow: hidden;
  flex: 1 1 400px
}

I've tried for instance:

<a href="website.html"><img src="001.jpg"></a>

And change the second part of the CSS to

.container a

instead of

.container img

But this, or other solutions that I've tried don't work, as the images don't grow or shrink when I change the window size.


Solution

  • Set image width as 100% so they cover entire width of the anchor element, then it will work as expected

    .container {
      margin: auto;
      display: flex;
      flex-flow: row wrap;
      justify-content: center;
    }
    
    .container a {
      overflow: hidden;
      flex: 1 1 400px;
    }
    
    img {
      width: 100%;
    }
    <div class="container">
      <a href="https://stackoverflow.com/"><img src="https://picsum.photos/id/1/200"></a>
      <a href="https://stackoverflow.com/"><img src="https://picsum.photos/id/11/200"></a>
      <a href="https://stackoverflow.com/"><img src="https://picsum.photos/id/111/200"></a>
    </div>