过渡与动画

CSS 教程 · 第 10 章 · 6 次浏览

过渡(transition)和动画(animation)为页面带来动态体验。过渡是状态变化的平滑过程,动画是定义关键帧的连续变化。

过渡 transition

声明 transition: 属性 时长 缓动,当该属性变化时平滑过渡。例如按钮 hover 变色。transition: all 0.3s ease 是最常用的写法。

动画 animation + keyframes

@keyframes 定义关键帧(from/to 或百分比),animation 属性应用动画:animation: 名称 时长 次数。常用缓动函数:ease、linear、ease-in-out。

性能建议:优先动画 transform 和 opacity(GPU 加速),避免动画布局属性(width、top)导致重排卡顿。

代码示例

<style>
.btn {
    padding: 10px 28px;
    background: #3b5bdb;
    color: #fff;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: transform 0.3s ease, background 0.3s ease;
}
.btn:hover {
    transform: translateY(-3px);   /* 上浮 */
    background: #2f4bc4;
}
@keyframes fadeInUp {
    from { opacity: 0; transform: translateY(20px); }
    to   { opacity: 1; transform: translateY(0); }
}
.banner {
    animation: fadeInUp 0.8s ease both;   /* both: 动画前后状态都应用 */
    padding: 30px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: #fff;
    border-radius: 12px;
}
</style>
<button class="btn">悬浮我</button>
<div class="banner" style="margin-top:20px;">入场动画</div>
📚 CSS 属性速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
写法 / 语法作用
color: #333;文字颜色
background: #fff;背景色 / 背景图
font-size: 16px;字号
font-family: Arial;字体
font-weight: bold;字重(加粗)
margin: 10px;外边距(上右下左)
padding: 10px;内边距
border: 1px solid #ccc;边框:粗细 样式 颜色
border-radius: 8px;圆角
width: 100%;宽度
height: 200px;高度
display: flex;弹性布局(现代布局主力)
display: none;隐藏元素
position: relative / absolute / fixed;定位方式
top / left / right / bottom定位偏移
text-align: center;文字水平对齐
line-height: 1.6;行高
overflow: hidden;内容溢出处理
box-shadow: 0 2px 8px rgba(0,0,0,.1);阴影
transition: all .3s;过渡动画
cursor: pointer;鼠标手型
z-index: 10;层叠顺序
max-width: 1200px; margin: 0 auto;容器居中(经典写法)
@media (max-width: 768px) {}响应式断点
:hover鼠标悬停状态