javascript – Make an image responsive inside a relative positioned container-ThrowExceptions

Exception or error:

I was trying to make a really simple slideshow with images appearing from right to left as animation:

let slides = document.querySelectorAll('.img-container');
let l = slides.length;
let i = 0;

setInterval(function(){
i = (i + 1) % l;
	if(i == 0){
		for(let j = l - 1;j != 0;j--){
			slides[j].classList.remove('img-slide');
		}
	} else {
		slides[i].classList.add('img-slide');
	}
}, 3500);
body {
	margin: 0px;
}

.section-1 {
	width: 100%;
	height: calc(100vh - 104.5px);
	overflow: hidden;
	display: flex;
}

.img-container {
	width: 100%;
	position: relative;
	display: flex;
	justify-content: center;
	transition: ease 0.7s;
}

.img-container:nth-child(1){
	z-index: 0;
}

.img-container:nth-child(2){
	z-index: 1;
}

.img-container:nth-child(3){
	z-index: 2;
}

.img-container:nth-child(4){
	z-index: 3;
}

.img-container:nth-child(2).img-slide{
	transform: translateX(-100%);
}

.img-container:nth-child(3).img-slide{
	transform: translateX(-200%);
}

.img-container:nth-child(4).img-slide{
	transform: translateX(-300%);
}
			<section class="section-1">
				<div class="img-container">
					<img src="https://i1.ytimg.com/vi/PKffm2uI4dk/maxresdefault.jpg">
				</div>
				<div class="img-container">
					<img src="https://i1.ytimg.com/vi/PKffm2uI4dk/maxresdefault.jpg">
				</div>
				<div class="img-container">
					<img src="https://i1.ytimg.com/vi/PKffm2uI4dk/maxresdefault.jpg">
				</div>
				<div class="img-container">
					<img src="https://i1.ytimg.com/vi/PKffm2uI4dk/maxresdefault.jpg">
				</div>		
			</section>

Those images are just an example so of course they appear stretched.
The images that i have to use are four different png images 4000×4000 with transparency so “img-container” must be the 100% of the body and also have a background color. The section must have a fixed height. The result with those images is kinda awful they look a bit stretched and on mobile some of those are cropped.
I tried to include

img {
   width: 100%;
   height: auto;
}

But the result was that all the four images became smaller and they all appeared simultaneously in the viewport. How can I fix that or where can I learn more about this topic?

How to solve:

To be able to achieve that you can use object-fit, object-fit: coveror object-fit: contain on the image tag

element.style {
    object-fit: cover;
}

Leave a Reply

Your email address will not be published. Required fields are marked *