css3制作时钟

使用CSS3制作时钟
通过CSS3的transform和animation属性可以创建一个简单的时钟效果,结合HTML结构实现时针、分针和秒针的动画。
HTML结构
<div class="clock">
<div class="hour-hand"></div>
<div class="minute-hand"></div>
<div class="second-hand"></div>
</div>
CSS样式
.clock {
width: 200px;
height: 200px;
border: 10px solid #333;
border-radius: 50%;
position: relative;
margin: 50px auto;
}
.hour-hand, .minute-hand, .second-hand {
position: absolute;
left: 50%;
bottom: 50%;
transform-origin: 50% 100%;
}
.hour-hand {
width: 6px;
height: 60px;
background: #333;
margin-left: -3px;
animation: rotate 43200s linear infinite;
}
.minute-hand {
width: 4px;
height: 80px;
background: #666;
margin-left: -2px;
animation: rotate 3600s linear infinite;
}
.second-hand {
width: 2px;
height: 90px;
background: #f00;
margin-left: -1px;
animation: rotate 60s linear infinite;
}
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
实现原理
- 时钟的圆形边框通过
border-radius: 50%实现。 - 时针、分针和秒针通过
position: absolute定位到中心,transform-origin设置旋转基点为底部。 animation属性控制旋转动画,时针每12小时(43200秒)旋转一圈,分针每小时(3600秒)旋转一圈,秒针每分钟(60秒)旋转一圈。
优化显示
可以添加刻度或数字增强视觉效果:
/* 添加时钟刻度 */
.clock::before {
content: "";
position: absolute;
width: 4px;
height: 15px;
background: #333;
left: 50%;
top: 10px;
margin-left: -2px;
transform-origin: 50% 90px;
}
/* 生成12个刻度 */
.clock::before {
transform: rotate(30deg);
}
.clock::after {
content: "";
position: absolute;
width: 4px;
height: 15px;
background: #333;
left: 50%;
top: 10px;
margin-left: -2px;
transform-origin: 50% 90px;
transform: rotate(60deg);
}
/* 继续添加其他刻度... */
注意事项
- 动画时间单位为秒,需根据实际需求调整。
- 如需实时同步系统时间,需结合JavaScript动态计算旋转角度。







