当前位置:首页 > CSS

css制作时钟

2026-01-08 11:56:34CSS

CSS 制作时钟的方法

使用纯 CSS 和少量 JavaScript 可以制作一个动态时钟。以下是实现步骤:

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 样式

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;
  background: #333;
  transform-origin: bottom center;
  left: 50%;
  top: 50%;
}

.hour-hand {
  width: 6px;
  height: 50px;
  margin-left: -3px;
  margin-top: -50px;
}

.minute-hand {
  width: 4px;
  height: 80px;
  margin-left: -2px;
  margin-top: -80px;
}

.second-hand {
  width: 2px;
  height: 90px;
  margin-left: -1px;
  margin-top: -90px;
  background: red;
}

.center {
  width: 12px;
  height: 12px;
  background: #333;
  border-radius: 50%;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -6px;
  margin-top: -6px;
  z-index: 10;
}

JavaScript 动态更新

function updateClock() {
  const now = new Date();
  const hours = now.getHours() % 12;
  const minutes = now.getMinutes();
  const seconds = now.getSeconds();

  const hourDeg = (hours * 30) + (minutes * 0.5);
  const minuteDeg = minutes * 6;
  const secondDeg = seconds * 6;

  document.querySelector('.hour-hand').style.transform = `rotate(${hourDeg}deg)`;
  document.querySelector('.minute-hand').style.transform = `rotate(${minuteDeg}deg)`;
  document.querySelector('.second-hand').style.transform = `rotate(${secondDeg}deg)`;
}

setInterval(updateClock, 1000);
updateClock();

实现原理

时钟的指针通过 CSS 的 transform: rotate() 属性实现旋转。JavaScript 计算当前时间对应的角度,每小时对应 30 度(360/12),每分钟对应 6 度(360/60),秒针同理。

css制作时钟

transform-origin: bottom center 确保指针围绕底部中心旋转。定时器每秒更新一次指针位置,实现动态效果。

增强样式

可以添加时钟刻度和数字增强视觉效果:

.clock::before {
  content: '';
  position: absolute;
  width: 4px;
  height: 12px;
  background: #333;
  left: 50%;
  top: 10px;
  margin-left: -2px;
}

/* 添加其他刻度类似 */

这种方法创建的时钟简洁高效,适合大多数网页场景。

标签: 时钟css
分享给朋友:

相关文章

css制作图标

css制作图标

使用CSS制作图标的方法 使用伪元素和边框 通过CSS的::before和::after伪元素结合border属性可以创建简单的几何形状图标。例如制作一个三角形: .triangle { w…

css制作表单

css制作表单

使用CSS制作表单的基本方法 创建一个美观且功能完善的表单需要结合HTML结构和CSS样式。以下是关键步骤和示例代码: HTML基础结构 <form class="my-form">…

表格制作css

表格制作css

基础表格样式 使用CSS可以轻松地为HTML表格添加样式。以下是一个基础表格的HTML和CSS示例: <table class="basic-table"> <thead>…

css制作相册

css制作相册

使用CSS Grid布局制作相册 CSS Grid布局非常适合创建响应式相册,能够灵活调整行列和间距。 .photo-gallery { display: grid; grid-templa…

网页制作 css

网页制作 css

CSS 基础语法 CSS(层叠样式表)用于控制网页的样式和布局。基本语法由选择器和声明块组成。选择器指向需要样式化的HTML元素,声明块包含一个或多个用分号分隔的声明,每个声明由属性和值组成。 选择…

css如何制作三角形

css如何制作三角形

使用边框属性制作三角形 通过设置元素的宽度和高度为0,利用边框属性可以创建三角形。边框的交汇处会形成斜边,通过设置不同边的颜色和透明度实现三角形效果。 .triangle { width: 0;…