当前位置:首页 > 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 样式

.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),秒针同理。

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

增强样式

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

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

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

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

css制作时钟

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

相关文章

react 如何引入css

react 如何引入css

在 React 中引入 CSS 的方法 React 提供了多种引入 CSS 的方式,可以根据项目需求选择合适的方法。以下是常见的几种方式: 内联样式 内联样式直接在组件中通过 style 属性定义…

css制作三角形

css制作三角形

使用 border 属性创建三角形 通过设置元素的 border 属性可以实现三角形效果。原理是利用边框的交界处形成的斜边。 .triangle { width: 0; height: 0;…

css网页制作教程

css网页制作教程

CSS网页制作教程 CSS(层叠样式表)是用于控制网页外观和布局的核心技术。以下是CSS网页制作的关键步骤和技巧: 基础语法与引入方式 CSS规则由选择器和声明块组成: 选择器 { 属性:…

制作css

制作css

CSS基础语法 CSS规则由选择器和声明块组成。选择器指向需要设置样式的HTML元素,声明块包含一个或多个用分号分隔的声明。每个声明由属性和值组成,用冒号分隔。 选择器 { 属性: 值;…

css 制作导航

css 制作导航

基础导航栏制作 使用HTML和CSS创建一个水平导航栏。HTML结构通常使用<ul>和<li>标签,CSS负责样式布局。 <nav> <ul class…

css导航制作

css导航制作

基础导航栏制作 使用HTML的无序列表 <ul> 和 <li> 构建导航结构,CSS清除默认样式并横向排列: <nav> <ul class="navb…