css制作钟表
使用CSS制作钟表
制作一个CSS钟表主要依赖CSS动画和transform属性,结合HTML结构实现时针、分针和秒针的旋转效果。

HTML结构
基础的HTML结构包含钟表的外壳和三个指针:

<div class="clock">
<div class="hand hour-hand"></div>
<div class="hand min-hand"></div>
<div class="hand sec-hand"></div>
</div>
CSS样式
通过CSS定义钟表的外观和指针动画:
.clock {
width: 200px;
height: 200px;
border: 10px solid #333;
border-radius: 50%;
position: relative;
margin: 50px auto;
}
.hand {
position: absolute;
bottom: 50%;
left: 50%;
transform-origin: 50% 100%;
}
.hour-hand {
width: 6px;
height: 50px;
background: #333;
transform: translateX(-50%) rotate(0deg);
animation: rotate-hour 43200s infinite linear;
}
.min-hand {
width: 4px;
height: 80px;
background: #666;
transform: translateX(-50%) rotate(0deg);
animation: rotate-min 3600s infinite linear;
}
.sec-hand {
width: 2px;
height: 90px;
background: #f00;
transform: translateX(-50%) rotate(0deg);
animation: rotate-sec 60s infinite linear;
}
@keyframes rotate-hour {
from { transform: translateX(-50%) rotate(0deg); }
to { transform: translateX(-50%) rotate(360deg); }
}
@keyframes rotate-min {
from { transform: translateX(-50%) rotate(0deg); }
to { transform: translateX(-50%) rotate(360deg); }
}
@keyframes rotate-sec {
from { transform: translateX(-50%) rotate(0deg); }
to { transform: translateX(-50%) rotate(360deg); }
}
实时动态效果
若需显示当前时间,可通过JavaScript动态计算指针角度:
function updateClock() {
const now = new Date();
const hour = now.getHours() % 12;
const min = now.getMinutes();
const sec = now.getSeconds();
document.querySelector('.hour-hand').style.transform =
`translateX(-50%) rotate(${(hour * 30) + (min * 0.5)}deg)`;
document.querySelector('.min-hand').style.transform =
`translateX(-50%) rotate(${min * 6}deg)`;
document.querySelector('.sec-hand').style.transform =
`translateX(-50%) rotate(${sec * 6}deg)`;
}
setInterval(updateClock, 1000);
updateClock(); // 初始化
细节优化
- 添加钟表刻度:通过伪元素在钟表边缘添加12个刻度标记。
- 中心点装饰:用一个小圆点覆盖指针根部,隐藏连接缝隙。
- 响应式设计:使用
vw/vh单位或媒体查询适配不同屏幕尺寸。






