Sudip Bhattarai
Sudip Bhattarai

Reputation: 138

How to make responsive image in carasoul while the images are in different sizes?

I’m having some trouble with the images in one of my pages. They are in a carousel, but as the carousel slides to the next image, it is constantly changing sizes because the images are different sizes. I have tried to set them all to be the same size, but it doesn’t seem to matter, they are still different sizes. What do I need to do to make it so they are the same size so the carousel will remain consistent through each slide?

Upvotes: 0

Views: 71

Answers (1)

Som Shekhar Mukherjee
Som Shekhar Mukherjee

Reputation: 8168

Using aspect-ratio

So, you can ignore the JavaScript and HTML in the snippet below.

In CSS what I've done is given a fixed width of 150px to all my images and a 1:1 aspect-ratio (because I know all my images are square).

Comment out the aspect-ratio code and you can see the difference.

let
  currImg = 0,
  totalImgs = 4;

const
  container = document.getElementById("container"),
  leftBtn = document.getElementById("left-btn"),
  rightBtn = document.getElementById("right-btn"),
  nav = (delta) => {
    container.children[currImg].classList.remove("show")
    currImg = (currImg + totalImgs + delta) % totalImgs
    container.children[currImg].classList.add("show")
  },
  navLeft = () => nav(-1),
  navRight = () => nav(1)

leftBtn.addEventListener("click", navLeft)
rightBtn.addEventListener("click", navRight)
img {
  width: 150px;
  aspect-ratio: 1/1;
  display: none;
  margin-bottom: 0.5rem;
}

.show {
  display: block;
}
<div id="container">
  <img src="https://placekitten.com/200/200" class="show" />
  <img src="https://placekitten.com/300/300" />
  <img src="https://placekitten.com/500/500" />
  <img src="https://placekitten.com/600/600" />
</div>
<button id="left-btn">Left</button>
<button id="right-btn">Right</button>

Upvotes: 1

Related Questions