css

transition用法

transition属性简介

Posted by Starrynight on 2024-02-23
Estimated Reading Time 2 Minutes
Words 517 In Total
Viewed Times

transition用法

🌈 一、transition 是什么?

transition 是 CSS 中的“过渡”属性,它能让某些 CSS 属性的变化变得有动画感,从 A 慢慢变成 B,而不是“瞬间切换”。


🧩 二、基本语法

1
transition: <property> <duration> <timing-function> <delay>;

这 4 个参数都是可选的,但顺序不能乱!

参数 说明 示例
property 要过渡的属性名 widthtransformopacity
duration 动画持续时间 0.5s200ms
timing-function 变速函数 easelinearease-in
delay 延迟时间 0.3s1s

🎯 三、常见写法示例

✅ 1. 缩放动画

1
2
3
4
5
6
.box {
transition: transform 0.3s ease;
}
.box:hover {
transform: scale(1.1);
}

鼠标移入 .box 元素时,会平滑放大。


✅ 2. 渐变颜色

1
2
3
4
5
6
7
.button {
background-color: #3498db;
transition: background-color 0.3s;
}
.button:hover {
background-color: #2ecc71;
}

鼠标移入按钮时,背景颜色会慢慢变绿。


✅ 3. 改变宽度

1
2
3
4
5
6
7
.bar {
width: 100px;
transition: width 0.5s ease-in-out;
}
.bar:hover {
width: 200px;
}

鼠标移入时宽度慢慢加倍。


💡 四、常用速记形式

示例 含义
transition: all 0.5s; 所有可动画的属性都过渡,持续 0.5 秒
transition: opacity 0.3s linear 0.2s; 透明度变化,线性,延迟 0.2 秒开始
transition: transform 0.3s ease, opacity 0.5s ease-in; 多个属性分别控制

⛔ 五、注意事项

  1. 不是所有属性都能加 transition,比如 display 不支持,常用的有:
    widthheightopacitycolorbackground-colortransformmargin 等。

  2. transition 只在属性值发生变化时才触发。
    所以你需要通过 :hover、JS 修改 class、状态切换等方式去改变属性值。

  3. transition 的性能高,因为浏览器对它优化过,推荐用在动画交互中


🚀 六、实战小练习:卡片放大 + 渐变阴影

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<style>
.card {
width: 200px;
height: 150px;
background: #fff;
box-shadow: 0 0 5px rgba(0,0,0,0.2);
transition: transform 0.3s ease, box-shadow 0.3s;
}
.card:hover {
transform: scale(1.05);
box-shadow: 0 8px 20px rgba(0,0,0,0.3);
}
</style>

<div class="card"></div>

🧠 效果:鼠标移入时卡片放大并提升阴影,有很强的“悬浮感”。



如果您喜欢此博客或发现它对您有用,则欢迎对此发表评论。 也欢迎您共享此博客,以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权,请与作者联系以将其删除。 谢谢 !