Cuenta atrás o countdown con HTML, CSS y JavaScript

Cuenta atrás o countdown con HTML, CSS y JavaScript con Sergio, profesor de SocraTech

Con el pretexto del año nuevo, nuestro profesor del bootcamp, Sergio Jiménez, nos enseña cómo hacer una cuenta atrás o countdown con HTML, CSS y JavaScript. Esto no es solo útil para contar los días que faltan para el nuevo año, sino que se puede utilizar para darle más visibilidad a una oferta por tiempo limitado dentro de la web, como para el Black Friday o las rebajas, entre otros usos.

En el siguiente vídeo puedes ver cómo Sergio, con su simpático gorro de Papá Noel, programa una cuenta atrás utilizando HTML, CSS y JavaScript.

Aceptar el consentimiento para ver esto

Como puedes ver, Sergio utiliza tres archivos, uno de HTML, otro de CSS y otro de JavaScript.

En primer lugar, se lleva a cabo el código en HTML para la cuenta atrás, con el siguiente resultado:

				
					<!DOCTYPE html>
<html lang="es">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/dist/confetti.browser.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <title>Cuenta atrás año nuevo</title>
  </head>
  <body>
    <main>
      <section class="container-start">
        <h1>🥳 Cuenta atrás para el 2025 🎉</h1>

        <div class="countdown">
          <div class="time-block">
            <span id="days"> 00 </span>
            <span class="label"> Días </span>
          </div>
          <div class="time-block">
            <span id="hours"> 00 </span>
            <span class="label"> Horas </span>
          </div>
          <div class="time-block">
            <span id="minutes"> 00 </span>
            <span class="label"> Minutos </span>
          </div>
          <div class="time-block">
            <span id="seconds"> 00 </span>
            <span class="label"> Segundos </span>
          </div>
        </div>
      </section>

      <section class="container-end">
        <h1>🎉 Feliz 2025 🎉</h1>
      </section>
    </main>

    <script src="index.js"></script>
  </body>
</html>
				
			

En el mismo archivo HTML, Sergio introduce algunas modificaciones de estilo para cambiar la fuente dentro de la etiqueta head, resultando el siguiente código:

				
					<!DOCTYPE html>
<html lang="es">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      @font-face {
        font-family: 'Snow For Santa';
        src: url('snow-for-santa/SnowForSanta.ttf') format('truetype');
      }

      body {
        font-family: 'Snow For Santa';
      }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/dist/confetti.browser.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <title>Cuenta atrás año nuevo</title>
  </head>
  <body>
    <main>
      <section class="container-start">
        <h1>🥳 Cuenta atrás para el 2025 🎉</h1>

        <div class="countdown">
          <div class="time-block">
            <span id="days"> 00 </span>
            <span class="label"> Días </span>
          </div>
          <div class="time-block">
            <span id="hours"> 00 </span>
            <span class="label"> Horas </span>
          </div>
          <div class="time-block">
            <span id="minutes"> 00 </span>
            <span class="label"> Minutos </span>
          </div>
          <div class="time-block">
            <span id="seconds"> 00 </span>
            <span class="label"> Segundos </span>
          </div>
        </div>
      </section>

      <section class="container-end">
        <h1>🎉 Feliz 2025 🎉</h1>
      </section>
    </main>

    <script src="index.js"></script>
  </body>
</html>
				
			

La fuente que se usa en el vídeo la puedes encontrar en el siguiente enlace: Snow For Santa.

Una vez se ha terminado con HTML, es el momento de pasar a maquetar la cuenta atrás con CSS:

				
					* {
  box-sizing: border-box;
  margin: 0;
}

body {
  min-height: 100vh;
  display: grid;
  place-items: center;
  text-transform: uppercase;
  color: white;
  background-image: linear-gradient(rgb(0 0 0 / 70%), rgb(0 0 0 / 70%)),
    url('./Snow.svg');
}

section {
  text-align: center;
  padding: 1.25rem;
}

.container-start h1 {
  margin-block-end: 3.125rem;
}

.container-end {
  display: none;
}

@keyframes wipe-in-down {
  from {
    clip-path: inset(0 0 100% 0);
  }
  to {
    clip-path: inset(0 0 0 0);
  }
}

h1 {
  font-size: clamp(3.75rem, 2.5rem + 3.333vw, 5rem);
  letter-spacing: 5px;
  text-wrap: balance;
  text-shadow: 0 0 5px #ffffff7c;
  transition: scale 0.3s;
  animation: wipe-in-down 2s cubic-bezier(0.25, 1, 0.3, 1) both;

  &:hover {
    scale: 1.05;
  }
}

@keyframes wipe-in-up {
  from {
    clip-path: inset(100% 0 0 0);
  }
  to {
    clip-path: inset(0 0 0 0);
  }
}

.countdown {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 1.875rem;

  .time-block {
    background-color: rgb(255 255 255 / 10%);
    padding: 1.25rem;
    border-radius: 1rem;
    backdrop-filter: blur(10px);
    min-width: 150px;
    box-shadow: 0 8px 32px rgb(0 0 0 / 10%);
    transition: transform 0.3s;
    display: flex;
    flex-direction: column;
    row-gap: 0.625rem;
    letter-spacing: 2px;

    &:nth-child(1) {
      animation: wipe-in-up 2.5s 0.5s cubic-bezier(0.25, 1, 0.3, 1) both;
    }

    &:nth-child(2) {
      animation: wipe-in-up 2.5s 1s cubic-bezier(0.25, 1, 0.3, 1) both;
    }

    &:nth-child(3) {
      animation: wipe-in-up 2.5s 1.5s cubic-bezier(0.25, 1, 0.3, 1) both;
    }

    &:nth-child(4) {
      animation: wipe-in-up 2.5s 2s cubic-bezier(0.25, 1, 0.3, 1) both;
    }

    &:hover {
      transform: translateY(-5px);
    }

    span:first-child {
      font-size: 4rem;
    }

    .label {
      font-size: 1.3rem;
      color: #ccc;
    }
  }
}
				
			

El fondo que utiliza Sergio lo puedes encontrar en el siguiente enlace: Snow. Mientras, las animaciones están en el siguiente enlace: Transitions.css.

Finalmente, se lleva a cabo el archivo JavaScript para la cuenta atrás o countdown, y queda así:

				
					const newYear = new Date('2025-01-01 00:00:00');

function formatTime(time) {
  return time.toString().padStart(2, '0');
}

function updateCountdown() {
  const now = new Date();
  const timeLeft = newYear - now;

  const days = Math.floor(timeLeft / 1000 / 60 / 60 / 24);
  const hours = Math.floor((timeLeft / 1000 / 60 / 60) % 24);
  const minutes = Math.floor((timeLeft / 1000 / 60) % 60);
  const seconds = Math.floor((timeLeft / 1000) % 60);

  const happyNewYear =
    days === 0 && hours === 0 && minutes === 0 && seconds === 0;

  if (happyNewYear) {
    clearInterval(countdownInterval);

    setInterval(() => {
      confetti({
        particleCount: 200,
        spread: 360,
        origin: {
          x: Math.random(),
          y: Math.random(),
        },
      });
    }, 1000);

    document.querySelector('.container-start').style.display = 'none';
    document.querySelector('.container-end').style.display = 'block';
  }

  document.getElementById('days').textContent = formatTime(days);
  document.getElementById('hours').textContent = formatTime(hours);
  document.getElementById('minutes').textContent = formatTime(minutes);
  document.getElementById('seconds').textContent = formatTime(seconds);
}

const countdownInterval = setInterval(updateCountdown, 1000);

updateCountdown();
				
			

Para mostrar el confeti cuando el countdown ha llegado a su fin, Sergio utiliza la librería que se encuentra en el siguiente enlace: Canvas Confetti.

Puedes encontrar todo el código también en este repositorio de GitHub: Cuenta atrás año 2025.

Y si quieres aprender más sobre HTML, CSS, JavaScript y muchas otras tecnologías, no dudes en echar un vistazo a nuestro Bootcamp Full Stack Web Developer, donde aprender a programar desde cero y convertirse en profesional.

Otros posts relacionados...