🛠️ Countdown timer: HTML and CSS

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

🛠️ Countdown timer: HTML and CSS

We are going to build a countdown timer together in this series. We’ll start by counting down to the end of this month. Then, to the end of the year. Then, a few years down the road.

It looks like this:

The countdown timer

Anatomy of the countdown timer

There are two parts in a countdown timer:

  1. The end date
  2. The countdown itself
Anatomy of a countdown timer

We can write the HTML like this:

<div class="countdown">
  <h1 class="countdown__target">Time to ...</h1>
  <div class="countdown__timer">...</div>
</div>

The end date

People use countdown timers to count to an event, like the launch of a product, end of sales, and start of a new year. If you’re using a countdown timer for that purpose, it makes sense to include the event in the timer.

Countdown timer on Learn JavaScript's salespage

For this countdown timer, we’ll count to a specific date instead.

Counting down to a date

Since we’re counting down to a date, we want to use the <time> element to create the date. We also want to include a datetime attribute.

<!-- Setting end date to 1 July, 2019 -->
<h1 class="countdown__target">Time to <time datetime="2019-07-01">1 July 2019</time></h1>

The countdown timer

To count to the end of this month, you need four different units:

  1. Days
  2. Hours
  3. Minutes
  4. Seconds

Each unit should be wrapped in its own HTML element since they’re independent of other units.

A valid HTML is:

<div class="countdown__timer">
  <div class="timer__box">
    <span class="timer__number">20</span>
    <span class"timer__unit">years</span>
  </div>
  <!-- ... -->
<div>

We can make the HTML simpler if you use a custom attribute selector (like data-unit) to create the units.

Here’s the HTML and CSS to do it:

<div class="countdown__timer">
  <div class="timer__box" data-unit="years">
    <span class="timer__number">20</span>
  </div>
<div>
.timer__box::after {
  content: attr(data-unit);
}

That’s it!

Let’s create the countdown next.