🛠️ How to Create a Simple Digital Clock with HTML, CSS, and JavaScript

In this tutorial, we'll build a clean digital clock from scratch using HTML, CSS, and JavaScript. This is a great project for beginners learning how to work with time and the DOM in JavaScript.


✅ What We’ll Build

A simple digital clock that:


🧱 Step 1: HTML Structure

Create a file named index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Digital Clock</title>
  <link rel="stylesheet" href="style.css" />
</head>
<body>
  <div class="clock" id="clock">00:00:00</div>
  <script src="script.js"></script>
</body>
</html>

What’s happening here?


🎨 Step 2: Styling the Clock (CSS)

Create a file named style.css:

body {
  margin: 0;
  padding: 0;
  background: #111;
  color: #0f0;
  font-family: 'Courier New', Courier, monospace;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.clock {
  font-size: 5rem;
  letter-spacing: 2px;
}

Highlights:


⏲️ Step 3: Add the JavaScript Logic

Create a file named script.js:

function updateClock() {
  const now = new Date();
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  const timeString = `${hours}:${minutes}:${seconds}`;
  document.getElementById('clock').textContent = timeString;
}

// Initial call to show clock immediately
updateClock();

// Update every second
setInterval(updateClock, 1000);

Breakdown:


🧪 Final Result

You should now see a working digital clock in your browser! 🎉


🧠 Extra Ideas to Try