提示
本文主要讲解 CSS 属性过渡的使用。@ermo
# CSS3 过渡 transition
CSS 过渡属性 transition
可以在给点的时间段内平滑地改版样式属性。过渡属性一般是配置 hover
使用。
下面为一个简单示例,用鼠标划过蓝色方块试试:
过渡的样式属性有以下几种:
transition
:简写属性,一个属性可以同时写下面四个属性transition-property
:需要过渡的属性名称transition-duration
:整个过渡过程的时间transition-delay
:过渡延迟执行的时间transition-timing-function
:过渡效果的类型
看一个简单例子:
.trs-all {
width: 100px;
height: 100px;
background-color: skyblue;
transition-property: width;
transition-duration: 1s;
transition-delay: .5s;
transition-timing-function: linear;
}
.trs-all:hover {
width: 200px
}
<div class="trs-all"></div>
# 如何使用过渡属性
创建过渡样式的有2个必要条件:
- 过渡样式要影响的属性值,比如宽度、颜色等
- 过渡样式执行的时间
看一个简单的示例:
<div class="tran-box"></div>
.tran-box {
width: 50px;
height: 50px;
background-color: red;
transition: width 2s;
}
.tran-box:hover {
width: 100px;
}
上例中当鼠标划入 div 盒子,宽度会在2秒内由 50px 逐渐变为 100px。
一般情况下过渡样式针对哪个盒子,transition
就放到哪个盒子上。比如当前例子,就应该放到 .tran-box
上。
# 多个属性过渡
针对多个属性使用过渡有2种书写方式。
第一种方式,将多个属性使用英文逗号隔开。
.tran-box {
width: 50px;
height: 50px;
background-color: red;
transition: width 2s, height 4s;
}
.tran-box:hover {
width: 100px;
height: 400px;
}
第二种方式,如果渐变时间是相同的,可以设定为全部属性 all
。
.tran-box {
width: 50px;
height: 50px;
background-color: red;
transition: all, 2s;
}
.tran-box:hover {
width: 100px;
height: 400px;
}
# transition-timing-function 过渡动画类型
transition-timing-function
表示过渡动画类型,可选值有:
linear
,以相同的速度完成整个过渡过程ease
,开始和结尾慢,中间快速ease-in
,以慢速开始过渡过程ease-out
,以慢速结束过渡过程ease-in-out
,以慢速开始,并以慢速结束的过渡过程
.trs-fun {
width: 100px;
height: 100px;
background-color: pink;
transition: all, 1s;
/* transition-timing-function: linear; */
transition-timing-function: ease;
}
.trs-fun:hover {
width: 200px;
height: 200px;
background-color: black;
}
# transition-delay 过渡延时开始
transition-delay
可以设置过渡延迟执行的时间。
下例中鼠标滑入
.trs-delay {
width: 100px;
height: 100px;
background-color: blue;
transition: all 1s;
transition-delay: 1s;
}
.trs-delay:hover {
width: 200px;
background: red;
}
# transition 和 transform 一起使用
.transform {
width: 100px;
height: 100px;
background-color: pink;
transition: width 1s, height 1s, transform 2s;
}
.transform:hover {
width: 150px;
height: 150px;
transform: rotate(180deg)
}
上例当鼠标划入盒子,盒子会旋转180度。