Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to add links to flexbox images?

This works (images with no links):

<div id="gallery">
     <img src="1.jpg"/>
     <img src="2.jpg"/>
     <img src="3.jpg"/>
     <img src="4.jpg"/>
</div>
 #gallery {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    padding: 0 4px;
  }
  
  #gallery img {
    width: 25%;
    height: 300px;
    object-fit: cover;
    margin-top: 8px;
    padding: 0 4px;
    border-radius: 10px;
  }

This totally messes up the .css (images with links):

<div id="gallery">
     <a href="1.jpg"><img src="1.jpg"/></a>
     <a href="2.jpg"><img src="2.jpg"/></a>
     <a href="3.jpg"><img src="3.jpg"/></a>
     <a href="4.jpg"><img src="4.jpg"/></a>
</div>

The only thing that makes it somewhat better is adding:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#gallery a {
    width: 100%;
}

But then it’s just a vertical stack of images.
So does flexbox just not allow images as links?

>Solution :

You need to re-apply the styles from img to a because flexbox applies to direct children only

#gallery {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  padding: 0 4px;
}

#gallery a {
  width: 25%;
  height: 300px;
  margin-top: 8px;
  padding: 0 4px;
  box-sizing: border-box;
}

#gallery img {
  border-radius: 10px;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div id="gallery">
  <a href="1.jpg"><img src="https://picsum.photos/200/300?random=1" /></a>
  <a href="2.jpg"><img src="https://picsum.photos/200/300?random=2" /></a>
  <a href="3.jpg"><img src="https://picsum.photos/200/300?random=3" /></a>
  <a href="4.jpg"><img src="https://picsum.photos/200/300?random=4" /></a>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading