css制作小时钟
使用CSS制作小时钟的方法
通过CSS的transform和animation属性可以模拟时钟指针的旋转效果,结合HTML结构实现一个动态的小时钟。
HTML结构
<div class="clock">
<div class="hour-hand"></div>
<div class="minute-hand"></div>
<div class="second-hand"></div>
<div class="center"></div>
</div>
CSS样式

.clock {
width: 200px;
height: 200px;
border: 10px solid #333;
border-radius: 50%;
position: relative;
background: #fff;
}
.hour-hand, .minute-hand, .second-hand {
position: absolute;
left: 50%;
bottom: 50%;
transform-origin: 50% 100%;
}
.hour-hand {
width: 6px;
height: 50px;
background: #333;
animation: rotate 43200s linear infinite; /* 12小时旋转一圈 */
}
.minute-hand {
width: 4px;
height: 80px;
background: #666;
animation: rotate 3600s linear infinite; /* 1小时旋转一圈 */
}
.second-hand {
width: 2px;
height: 90px;
background: #f00;
animation: rotate 60s linear infinite; /* 1分钟旋转一圈 */
}
.center {
width: 12px;
height: 12px;
background: #333;
border-radius: 50%;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
添加时钟刻度和数字
通过伪元素或额外HTML元素添加时钟的刻度标记:
.clock::before {
content: "";
position: absolute;
width: 90%;
height: 90%;
border-radius: 50%;
top: 5%;
left: 5%;
background: transparent;
}
/* 添加12个刻度 */
.clock::after {
content: "";
position: absolute;
width: 4px;
height: 15px;
background: #333;
top: 10px;
left: 50%;
transform: translateX(-50%);
}
使用JavaScript实现实时更新
通过JavaScript获取当前时间,动态计算指针角度:

function updateClock() {
const now = new Date();
const hours = now.getHours() % 12;
const minutes = now.getMinutes();
const seconds = now.getSeconds();
document.querySelector('.hour-hand').style.transform =
`rotate(${hours * 30 + minutes * 0.5}deg)`;
document.querySelector('.minute-hand').style.transform =
`rotate(${minutes * 6}deg)`;
document.querySelector('.second-hand').style.transform =
`rotate(${seconds * 6}deg)`;
}
setInterval(updateClock, 1000);
updateClock(); // 初始化
响应式设计
通过CSS变量或媒体查询调整时钟大小:
:root {
--clock-size: min(90vw, 300px);
}
.clock {
width: var(--clock-size);
height: var(--clock-size);
}
美化效果
添加阴影和渐变效果增强视觉体验:
.clock {
box-shadow: 0 0 20px rgba(0,0,0,0.2);
background: radial-gradient(circle, #f9f9f9, #ddd);
}
.second-hand {
box-shadow: 0 0 5px rgba(255,0,0,0.5);
}






