1、过渡
1.1 从这边到那边
html部分
<button>Hover over me</button>
css部分
button {
background-color: hsl(180, 50%, 50%); //蓝绿色按钮
border: 0;
color: white;
font-size: 1rem;
padding: .3em 1em;
transition-property: all; //所有属性变化都使用过渡结果
transition-duration: 0.5s; //过渡时间为0.5s
}
button:hover {
//悬停状态为带圆角的红色按钮
background-color: hsl(0, 50%, 50%);
border-radius: 1em;
}
transition-property 这个属性可以指定哪些属性使用过渡,比如只过渡颜色
transition-property: color
transition-duration 属性代表过渡到最终值之前需要多长时间,本例中设置为 0.5s,代表 0.5s
也可以使用简写属性 transition,该简写属性接受四个参数值,分别 代表四个过渡属性 transition-property(生效属性)、transition-duration(持续时间)、transition-timing-function(定时函数)和transition-delay(延迟时间)
transition: background-color 0.3s linear 0.5s
如果需要为两个不同的属性分别设置不同的过渡,可以添加多个过渡规则,以逗号分隔,如下代码所示。
transition: border-radius 0.3s linear, background-color 0.6s ease;
1.2 定时函数
定时函数是过渡中非常重要的一部分。过渡让某个属性从一个值“移动”到另一个值,定时函数用来说明如何移动
我们可以使用几个关键字值来描述移动过程,比如 linear、ease-in 和 ease-out。使用 linear 过渡,值以固定的速度改变;使用 ease-in,变化速度开始时慢,然后一直加速,直到 过渡完成;ease-out 是减速,开始时快速变化,结束时比较慢。
<div class="container">
<div class="box"></div> //这个盒子将从屏幕左边过渡到右边
</div>
接下来为盒子设置样式,添加一些颜色和大小。然后为盒子绝对定位,当鼠标悬停时移动它的位置
.container {
position: relative; height: 30px;
}
.box {
position: absolute;
left: 0;
height: 30px;
width: 30px;
background-color: hsl(130, 50%, 50%);
transition: all 1s linear;
}
.container:hover .box {
left: 400px;
}
1.3 阶跃
阶跃函数需要两个参数:阶跃次数和一个用来表示每次变化发生在阶跃的开始还是结束的关键词(start 或者 end)
<style>
.container {
position: relative;
height: 30px;
}
.box {
position: absolute;
left: 0;
height: 30px;
width: 30px;
background-color: hsl(130, 50%, 50%);
transition: all 1s steps(3);
}
.container:hover .box {
left: 400px;
}
</style>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
2、变换
- 旋转(Rotate)——元素绕着一个轴心转动一定角度
- 平移(Translate)——元素向上、下、左、右各个方向移动(有点类似于相对定位)
- 缩放(Scale)——缩小或放大元素。
- 倾斜(Skew)——使元素变形,顶边滑向一个方向,底边滑向相反的方向
每种变换都使用相应的函数作为 transform 属性的值
2.1.1 更换变换基点
可以通过 transform-origin 属性改变基点位置
左侧的元素绕基点旋转,其基点设置为 transform-origin: right bottom;中间的元 素向着基点(right top)缩放;右侧元素的倾斜方式是,基点(left top)保持不动,元素 其他部分向远处延伸。
基点也可以指定为百分比,从元素左上角开始测量。下面的两句声明是等价的。 transform-origin: right center; transform-origin: 100% 50%
也可以使用 px、em 或者其他单位的长度值来指定基点。按照我的经验,使用 top、right、bottom、left 和 center 这些关键字,在大部分项目中就够用了。
2.1.2 使用多重变换
可以对 transform 属性指定多个值,用空格隔开。变换的每个值从右向左按顺序执行,比 如我们设置 transform: rotate(15deg) translate(15px, 0),元素会先向右平移 15px, 然后顺时针旋转 15 度
<style>
body {
/* background-color: hsl(210, 80%, 20%); */
font-family: Helvetica, Arial, sans-serif;
}
img {
max-width: 100%;
}
.card {
padding: 0.5em;
margin: 0 auto;
background-color: rgb(238, 175, 175);
max-width: 300px;
transform: rotate(15deg) translate(20px, 0);
}
</style>
<body>
<div class="card">
<img src="./th.png" alt="a chicken" />
<h4>Mrs. Featherstone</h4>
<p>
She may be a bit frumpy, but Mrs Featherstone gets the job done.
She lays her largish cream-colored eggs on a daily basis. She is
gregarious to a fault.
</p>
<p>This Austra White is our most prolific producer.</p>
</div>
</body>