过渡效果

CSS3 教程 · 第 5 章 · 8 次浏览

transition 让样式变化不是瞬间跳变,而是平滑过渡。它通常配合 hover、focus 或者 JavaScript 改样式时使用。

写法

transition: 属性 时长 速度曲线 延迟。比如 transition: background .3s ease。多个属性用逗号分隔,或者用 transition: all .3s(不推荐 all,性能略差)。

速度曲线 easing

  • ease:慢-快-慢,默认
  • linear:匀速
  • ease-in:加速进入
  • ease-out:减速退出
  • cubic-bezier(x1,y1,x2,y2):自定义曲线

注意:transition 只能过渡可计算的属性(颜色、尺寸、透明度、变换),display 这种不能过渡。

代码示例

.link {
    color: #333;
    border-bottom: 2px solid transparent;
    transition: color .2s, border-color .3s ease;
}
.link:hover {
    color: #7cb342;
    border-color: #7cb342;
}

.button {
    background: #558b2f;
    transition: all .3s cubic-bezier(.4, 0, .2, 1);
}
.button:hover {
    background: #33691e;
    box-shadow: 0 6px 16px rgba(85,139,47,.4);
}
📚 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鼠标悬停状态