Analog Clock with HTML, CSS & JavaScript
01/19/2021
Demo
Video
Code
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Analog Clock with HTML, CSS & JavaScript</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="clock">
<div id="hour"></div>
<div id="minute"></div>
<div id="second"></div>
</div>
<script src="clock.js"></script>
</body>
</html>
CSS
@charset "utf-8";
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100vh;
background-color: #112c4f;
}
.clock {
position: relative;
width: 300px;
height: 300px;
background-image: url(clock.png);
background-position: center;
background-size: 100%;
background-repeat: no-repeat;
}
.clock::before {
position: absolute;
top: 50%;
left: 50%;
z-index: 999;
transform: translate(-50%, -50%);
width: 16px;
height: 16px;
border-radius: 50%;
background-color: #3d3935;
content: '';
}
#hour {
position: absolute;
top: 25%;
left: calc(50% - 4px);
transform-origin: bottom;
width: 8px;
height: 25%;
border-radius: 4px 4px 0 0;
background-color: #112c4f;
}
#minute {
position: absolute;
top: 15%;
left: calc(50% - 3px);
transform-origin: bottom;
width: 6px;
height: 35%;
border-radius: 3px 3px 0 0;
background-color: #e9c277;
}
#second {
position: absolute;
top: 8%;
left: calc(50% - 1px);
transform-origin: bottom;
width: 2px;
height: 42%;
border-radius: 1px 1px 0 0;
background-color: #d73659;
}
@media screen and (max-width: 480px) {
.clock {
width: 200px;
height: 200px;
}
}
JavaScript
const hour = document.getElementById("hour");
const minute = document.getElementById("minute");
const second = document.getElementById("second");
function clock() {
const d = new Date();
const hr = d.getHours();
const min = d.getMinutes();
const sec = d.getSeconds();
const hrDeg = 30 * hr + min / 2;
const minDeg = 6 * min;
const secDeg = 6 * sec;
hour.style.transform = `rotate(${hrDeg}deg)`;
minute.style.transform = `rotate(${minDeg}deg)`;
second.style.transform = `rotate(${secDeg}deg)`;
}
setInterval(clock, 1000);