纯css制作钟表

纯CSS制作钟表
使用纯CSS制作钟表主要依赖于CSS的transform和animation属性,结合伪元素(::before、::after)实现表盘、时针、分针和秒针的效果。以下是实现方法:

HTML结构
<div class="clock">
<div class="hour-hand"></div>
<div class="minute-hand"></div>
<div class="second-hand"></div>
<div class="center-dot"></div>
</div>
CSS样式
.clock {
width: 200px;
height: 200px;
border: 10px solid #333;
border-radius: 50%;
position: relative;
margin: 50px auto;
background: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.hour-hand {
width: 6px;
height: 50px;
background: #333;
position: absolute;
top: 50%;
left: 50%;
transform-origin: bottom center;
transform: translate(-50%, -100%) rotate(30deg);
animation: rotate-hour 43200s linear infinite;
}
.minute-hand {
width: 4px;
height: 80px;
background: #666;
position: absolute;
top: 50%;
left: 50%;
transform-origin: bottom center;
transform: translate(-50%, -100%) rotate(90deg);
animation: rotate-minute 3600s linear infinite;
}
.second-hand {
width: 2px;
height: 90px;
background: #f00;
position: absolute;
top: 50%;
left: 50%;
transform-origin: bottom center;
transform: translate(-50%, -100%) rotate(180deg);
animation: rotate-second 60s linear infinite;
}
.center-dot {
width: 12px;
height: 12px;
background: #333;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
@keyframes rotate-hour {
from { transform: translate(-50%, -100%) rotate(0deg); }
to { transform: translate(-50%, -100%) rotate(360deg); }
}
@keyframes rotate-minute {
from { transform: translate(-50%, -100%) rotate(0deg); }
to { transform: translate(-50%, -100%) rotate(360deg); }
}
@keyframes rotate-second {
from { transform: translate(-50%, -100%) rotate(0deg); }
to { transform: translate(-50%, -100%) rotate(360deg); }
}
实现原理
- 表盘:通过
border-radius: 50%将div变为圆形,边框模拟表盘外框。 - 指针:使用绝对定位的
div模拟时针、分针和秒针,通过transform-origin设置旋转中心为底部。 - 动画:利用
@keyframes定义旋转动画,时针周期为12小时(43200秒),分针为1小时(3600秒),秒针为60秒。 - 中心点:通过小圆点模拟钟表中心。
刻度标记(可选)
若需添加刻度,可通过伪元素实现:
.clock::before {
content: "";
position: absolute;
width: 4px;
height: 15px;
background: #333;
top: 10px;
left: 50%;
transform: translateX(-50%);
}
/* 其他刻度类似,通过rotate调整角度 */
通过调整CSS变量(如颜色、尺寸)和动画时间,可自定义钟表样式。此方法无需JavaScript,完全依赖CSS动画实现动态效果。






