CSS transition:比较持续时间、延迟与缓动
CSS 的 transition 在属性计算值发生变化时,按时间呈现起始值和目标值之间的中间状态。示例在勾选或取消复选框时改变方块的 transform 和 background-color。
读懂过渡属性、时间与缓动设置
| 设置 | 作用和示例 |
|---|---|
transition-property |
指定参与过渡的属性,例如 transform 或 background-color。 |
transition-duration |
指定变化持续的时间。0.8s 等于 800ms。 |
transition-timing-function |
控制过渡进度。linear 匀速推进,ease 则改变进度节奏。 |
transition-delay |
调整起点。正值先等待,负值从过渡中的某一时刻开始。 |
transition-behavior |
默认值是 normal。allow-discrete 允许受支持的离散属性发生过渡。 |
在 transition: transform 0.8s ease 0.3s 中,transform 等待 0.3 秒后,用 0.8 秒完成过渡。第一个时间是持续时间,第二个是延迟。多个条目用逗号隔开,明确列出目标属性可以避免 all 让其他属性也发生过渡。参见 CSS Transitions · Shorthand。
用复选框触发过渡
将代码保存为 transition.html 并打开。可以点击复选框,也可以用 Tab 聚焦后按空格切换状态。示例不需要外部文件或 JavaScript。
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用复选框体验过渡</title>
<style>
body { margin: 20px; font: 16px/1.6 system-ui, sans-serif; color: #203348; }
* { box-sizing: border-box; }
h1 { font-size: 24px; }
label { display: inline-block; padding: 10px 4px; }
.stage { max-width: 500px; margin-top: 16px; padding: 12px;
border: 1px solid #8fa6ba; background: #edf3fa; }
.box { display: grid; place-items: center; width: 80px; height: 80px;
color: white; background-color: #1768a5; transform: translateX(0);
transition: transform 0.8s ease, background-color 0.8s linear; }
#move:checked ~ .stage .box { transform: translateX(150px); background-color: #087b76; }
@media (prefers-reduced-motion: reduce) {
.box { transition: none; }
}
</style>
</head>
<body>
<h1>比较过渡前后的状态</h1>
<input id="move" type="checkbox">
<label for="move">向右移动方块</label>
<div class="stage"><div class="box">方块</div></div>
<p>勾选后方块移动并变色,取消勾选后恢复初始状态。</p>
</body>
</html>
勾选后,方块向右移动 150px,并从蓝色变为青绿色。如果没有开启减少动态效果,且中途没有切换状态,两项变化都会在 0.8 秒内达到目标值。移动使用 ease,颜色变化使用 linear,因此进度不同。
比较延迟、持续时间和缓动方式
在 .box 基础规则的简写声明后添加 transition-delay: 0.5s,两项变化都会等待半秒。再改成 -0.4s,页面会立即显示 0.8 秒过渡中已经过去 0.4 秒的状态。使用 ease 时,经过一半时间不一定走完一半距离。对比后删除该声明。
在相同位置加上 transition-duration: 2s,两项过渡都会持续两秒。移除这条声明后,只把 transform 条目中的 ease 改成 linear。这样可以在距离和时长一致的情况下比较速度曲线,结束后恢复原值。
排查没有过渡或返回时直接跳变的问题
把过渡写在 .box 基础规则里,取消勾选时也能继续应用。如果只写在勾选状态中,返回时可能直接跳回原值。过渡途中反向切换时,浏览器可能从当前显示值继续,返回耗时也可能缩短。参见 CSS Transitions · Starting Transitions。
如果看不到过渡,请检查起止计算值是否不同、目标属性是否被列出,以及持续时间是否大于零。如果启用了 prefers-reduced-motion: reduce,示例通过 transition: none 跳过中间动画,位置和颜色仍会更新。参见 Media Queries · Reduced Motion。




