Search code examples
htmlcssflexboxgrid

Responsive display: flex; depending on image orientation


Seems like something quite easy to be achieved, but I'm trying to figure out the simpliest way to do it.

I'm basically having two types of images on my page: portrait and landspace.

  • I would like the landscapes picture to take full width of the parent div,
  • and the portrait pictures to be 2 by row.

& this dynamically, without having to invoke the :nth-child selector.

enter image description here

main{
  background: orange;
  width: 60vw;
}

section{
  width: 100%;
  display: flex;
  flex-wrap: wrap;

}

img{
  flex: 1;
 /* width: 100%; */
}
<main>
  <section>
    <img src="https://picsum.photos/200/300" alt="" class="hero">
    <img src="https://picsum.photos/200/320" alt="" class="hero">
    <img src="https://picsum.photos/600/300" alt="" class="hero">
    <img src="https://picsum.photos/200/300" alt="" class="hero">
    <img src="https://picsum.photos/700/300" alt="" class="hero">


  </section>
</main>


Solution

  • You can get aspect ratio using js and then apply styling based on it.

    const images = document.querySelectorAll('.hero')
    
    images.forEach((image) => {
      image.addEventListener('load', function() {
        let width = image.offsetWidth;
        let height = image.offsetHeight;
        let ratio = width / height;
    
        if (ratio < 1) {
          image.classList.add('portrait')
        } else {
          image.classList.add('landscape')
        }
      });
    })
    main {
      background: orange;
      width: 60vw;
    }
    
    section {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
    }
    
    img {
      width: 100%;
    }
    
    .portrait {
      width:  50%;
    }
    <main>
      <section>
        <img src="https://picsum.photos/200/300" alt="" class="hero">
        <img src="https://picsum.photos/200/320" alt="" class="hero">
        <img src="https://picsum.photos/600/300" alt="" class="hero">
        <img src="https://picsum.photos/200/300" alt="" class="hero">
        <img src="https://picsum.photos/700/300" alt="" class="hero">
    
    
      </section>
    </main>