🛠️ 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:
- Shows the current time (hours, minutes, and seconds)
- Updates every second
- Uses only HTML, CSS, and vanilla JavaScript
🧱 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?
- We create a
<div>with the IDclockto display the time. - CSS is linked via
style.css. - JavaScript is loaded with
script.js.
🎨 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:
- Fullscreen dark background
- Green glowing digits for that retro digital clock vibe
- Centered layout using Flexbox
⏲️ 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:
new Date()gets the current system time.padStart(2, '0')ensures 2-digit formatting (e.g.,08instead of8).setIntervalupdates the clock every 1000 milliseconds (1 second).
🧪 Final Result
You should now see a working digital clock in your browser! 🎉
🧠 Extra Ideas to Try
- Add AM/PM format
- Show date (e.g.,
Monday, April 25, 2025) - Allow theme switching (light/dark mode)
- Animate the seconds or blinking colons