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.
& this dynamically, without having to invoke the :nth-child
selector.
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>
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>