css时钟制作
CSS时钟制作方法
制作一个纯CSS时钟无需JavaScript,利用CSS动画和伪元素实现时间显示。以下是具体实现步骤:
HTML结构
<div class="clock">
<div class="hour"></div>
<div class="minute"></div>
<div class="second"></div>
</div>
CSS样式
.clock {
width: 300px;
height: 300px;
border-radius: 50%;
background: #fff;
border: 10px solid #333;
position: relative;
box-shadow: 0 0 20px rgba(0,0,0,0.2);
}
.hour, .minute, .second {
position: absolute;
left: 50%;
bottom: 50%;
transform-origin: 50% 100%;
}
.hour {
width: 8px;
height: 80px;
background: #333;
margin-left: -4px;
animation: rotate 43200s linear infinite;
}
.minute {
width: 4px;
height: 120px;
background: #666;
margin-left: -2px;
animation: rotate 3600s linear infinite;
}
.second {
width: 2px;
height: 140px;
background: red;
margin-left: -1px;
animation: rotate 60s linear infinite;
}
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
刻度添加
.clock::before {
content: '';
position: absolute;
width: 20px;
height: 20px;
background: #333;
border-radius: 50%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 10;
}
/* 添加12个刻度 */
.clock::after {
content: '';
position: absolute;
width: 5px;
height: 15px;
background: #333;
top: 10px;
left: 50%;
margin-left: -2.5px;
transform-origin: 50% 140px;
}
/* 创建12个刻度 */
.clock::after {
box-shadow:
0 60px 0 0 #333,
0 120px 0 0 #333,
0 180px 0 0 #333,
0 240px 0 0 #333,
0 300px 0 0 #333;
}
/* 添加小时数字(可选) */
.clock span {
position: absolute;
font-family: Arial;
font-size: 24px;
font-weight: bold;
color: #333;
}
动态时钟实现
要使时钟显示真实时间,需要结合JavaScript:
function updateClock() {
const now = new Date();
const hour = now.getHours() % 12;
const minute = now.getMinutes();
const second = now.getSeconds();
const hourDeg = (hour * 30) + (minute * 0.5);
const minuteDeg = minute * 6;
const secondDeg = second * 6;
document.querySelector('.hour').style.transform = `rotate(${hourDeg}deg)`;
document.querySelector('.minute').style.transform = `rotate(${minuteDeg}deg)`;
document.querySelector('.second').style.transform = `rotate(${secondDeg}deg)`;
}
setInterval(updateClock, 1000);
updateClock();
响应式调整
添加媒体查询使时钟适应不同屏幕:
@media (max-width: 600px) {
.clock {
width: 200px;
height: 200px;
}
.hour { height: 50px; }
.minute { height: 80px; }
.second { height: 90px; }
}
高级样式优化
添加阴影和渐变效果:
.clock {
background: radial-gradient(circle, #fff 0%, #eee 100%);
box-shadow:
inset 0 0 15px rgba(0,0,0,0.1),
0 0 30px rgba(0,0,0,0.2);
}
.hour, .minute {
box-shadow: 0 0 5px rgba(0,0,0,0.3);
}
以上代码组合可创建一个美观且功能完整的CSS时钟,纯CSS版本适合展示动画原理,结合JavaScript的版本可实现真实时间显示。







