css教程网 css教程网365css.cn
公告为您打开互联网世界的窗户关于本站
首页/实战/正文
RECIPES · 实战

CSS 动画:只动 transform 和 opacity

为什么改 width 会卡、缓动曲线怎么选、will-change 什么时候反而是负担。

更新于 2026-10-24 阅读约 10 分钟 标签 动画 / 性能

动画卡不卡,基本在写第一行就决定了:动 transform 和 opacity 流畅,动 width、top、margin 一定卡。因为前者只需要合成层重新合成,后者要重新计算布局并重绘整棵子树。

用 transform 代替位移属性#

CSS
/* 卡:每帧都在重新布局 */
.move { transition: left .3s; left: 0; }
.move:hover { left: 20px; }

/* 顺:只走合成 */
.move { transition: translate .3s; translate: 0 0; }
.move:hover { translate: 20px 0; }

translate / scale / rotate 是独立的变换属性,比写 transform: translateX() 更易读,也不会互相覆盖。

缓动曲线决定「手感」#

  • linear:匀速,只适合进度条、旋转 loading。
  • ease:默认值,两端慢中间快,比较中庸。
  • ease-out:快进慢出,适合「进入」——元素出现时更有存在感。
  • ease-in:慢进快出,适合「离开」。
  • cubic-bezier(.2,.9,.3,1):自定义的「果冻感」,界面动效常用。
CSS
.panel { transition: transform .28s cubic-bezier(.2, .9, .3, 1), opacity .2s ease; }

一个经验:进入用 ease-out,离开用 ease-in,位移距离越大时长越长。超过 400ms 的界面动画会让人觉得「卡」,除了刻意的过场。

交错动画:用 nth-child 做延迟#

CSS
.item { animation: rise .5s cubic-bezier(.2, .9, .3, 1) both; }
.item:nth-child(1) { animation-delay: 0ms; }
.item:nth-child(2) { animation-delay: 60ms; }
.item:nth-child(3) { animation-delay: 120ms; }

更省事的写法是用自定义属性配合 style="--i:1",延迟写成 calc(var(--i) * 60ms)。列表项数量不固定时尤其方便。

will-change 不是万金油#

它的作用是提前告诉浏览器「这个元素要变了」,让浏览器提前提升为合成层。但每个合成层都要占显存,滥用会导致内存暴涨、滚动反而更卡。

CSS
/* 只在实际要动画的元素上,且动画结束后移除 */
.card:hover { will-change: transform; }

尊重 reduced-motion#

CSS
@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: .01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: .01ms !important;
    scroll-behavior: auto !important;
  }
}

注意这条规则要放在样式表最后,否则会被后面的动画声明覆盖。它不是「可选的礼貌」,是避免让部分用户头晕的必要措施。

一个完整的入场动画#

CSS
@keyframes rise {
  from { opacity: 0; transform: translateY(12px); }
  to   { opacity: 1; transform: none; }
}
.hero-title {
  animation: rise .6s cubic-bezier(.2, .9, .3, 1) both;
}
/* both 让元素在动画开始前就应用第一帧,避免闪现 */

实战部分到这里结束。回到基础把模型再捋一遍,或者去片段库找现成写法。