Skip to content

Image carousel in HTML and CSS

A photo carousel with previous, next, dots and a pause button, which never advances on its own when the user reduces motion.

Here is an excerpt of this component's code in HTML and CSS. The full code is free for members, ready to copy into your project.

This component also comes in

Open in a new tab

The code in HTML and CSS

carousel.js
document.querySelectorAll("[data-carousel]").forEach((root) => {
  const slides = [...root.querySelectorAll("[data-slide]")];
  const dots = [...root.querySelectorAll("[data-carousel-dot]")];
  const track = root.querySelector("[data-carousel-slides]");
  const toggle = root.querySelector("[data-carousel-toggle]");
  let index = 0;
  let playing = !window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  let hovered = false;
  let timer;

  function show(next) {
    index = (next + slides.length) % slides.length;
index.html
<!doctype html>
<html lang="fr">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Carrousel d'images</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <main class="demo">
      <section class="pcar" aria-roledescription="carrousel" aria-label="Photos du Mas des Oliviers" data-carousel>
        <div class="pcar__slides" id="pcar-slides" data-carousel-slides>
style.css
:root {
  --pc-text: #042f2e;
  --pc-muted: #3f6260;
  --pc-card: #ffffff;
  --pc-line: #bfe3de;
  --pc-accent: #0f766e;
  --pc-dot: #8fbfb9;
  --pc-ring: #134e4a;
  --pc-shadow: 0 10px 30px -18px rgb(4 47 46 / 0.5);
  --demo-bg: #f0fbfa;
  --demo-text: #042f2e;
}

Free component: copy it freely, including for commercial projects.

Galleries and carousels components in HTML and CSS
  • A product photo that zooms in under the pointer, and from the keyboard with Enter and the arrow keys, to inspect the details.

    • Tailwind
    • React
    • CSS
    • WordPress
    Component
  • Building site photos sorted by dated step on a vertical timeline, with the current step highlighted.

    • Tailwind
    • React
    • CSS
    • WordPress
    Component
  • YouTube videos shown as thumbnails: the player only loads on click, to respect privacy and keep the page light.

    • Tailwind
    • React
    • CSS
    • WordPress
    Component
  • A slideshow that fills the whole screen, browsed with the keyboard or a finger swipe, and closed with Escape.

    • Tailwind
    • React
    • CSS
    • WordPress
    Component