<!--
Forum answer only:
https://www.sitepoint.com/community/t/javascript-image-carousel/432946/7
-->
<div class="carousel">
  <div class="image-container" id="imgs">
    <img src="https://picsum.photos/id/1015/1500/500" alt="pic1" width="500px" height="500px">
    <img src="https://picsum.photos/id/1016/1500/500" alt="pic2" width="500px" height="500px">
    <img src="https://picsum.photos/id/1018/1500/500" alt="pic3" width="500px" height="500px">
    <img src="https://picsum.photos/id/1019/1500/500" alt="pic4" width="500px" height="500px">
    <img src="https://picsum.photos/id/1021/1500/500" alt="pic5" width="500px" height="500px">
  </div>
  <div class="button-container">
    <button id=" button-prev" class="btn">Previous</button>
    <button id="button-next" class="btn">Next</button>
  </div>
</div>
/*
Forum answer only:
https://www.sitepoint.com/community/t/javascript-image-carousel/432946/7
*/

html {
  box-sizing: border-box;
}
*,
*:before,
*:after {
  box-sizing: inherit;
}
html,
body {
  margin: 0;
  padding: 0;
}
body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
    Arial, sans-serif;
  background: #ccc;
  padding: 20px;
}

.carousel {
  display: flex;
  flex-direction: column;
  max-width: 1480px;
  margin: auto;
}
.image-container {
  display: flex;
  margin: 20px auto;
  outline: 10px solid red;
  width: 100%;
  aspect-ratio: 3 / 1;
  overflow: hidden;
}
.button-container {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem 0;
}
.image-container img {
  transition: 0.8s ease;
  width: 100%;
  height: auto;
  object-fit: cover;
}
/*
Forum answer only:
https://www.sitepoint.com/community/t/javascript-image-carousel/432946/7
*/

const imgs = document.getElementById("imgs");
const btnPrev = document.getElementById("button-prev");
const btnNext = document.getElementById("button-next");
const slides = document.querySelectorAll(".image-container img");
let index = 0;

const slider = () => {
  if (index === slides.length - 1) {
    index = 0;
  } else {
    index++;
  }

  slides.forEach((slide) => {
    slide.style.transform = `translateX(${-index * 100}%)`;
  });
};
const interval = setInterval(slider, 5000);

slider();
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.