一、2D 变换(transform)
位移(translate)
translateX(100px):水平向右移动 100px,百分比值是相对于元素自身宽高。
translateY(50%):垂直向下移动自身高度的 50%。
示例:transform: translateX(100px); 让红色方块水平右移 100px。
旋转(rotate)
rotate(45deg):以元素中心为原点旋转 45 度。
可通过 transform-origin 改变旋转原点,如 transform-origin: left top; 会让元素以左上角为原点旋转。
缩放(scale)
scale(0.5):让元素整体缩小到原来的 50%,scale(2) 则放大到 2 倍。
示例:.box:hover { transform: scale(0.5); } 实现鼠标悬停时方块缩小效果。
二、过渡动画(transition)
作用:让 CSS 属性变化时产生平滑过渡效果,而不是瞬间切换。
核心语法:transition: property duration timing-function;
property:要监听的属性,all 表示监听所有属性变化。
duration:过渡时间,如 1s 表示 1 秒完成过渡。
timing-function:过渡速度曲线,如 linear 表示匀速过渡。
示例:
css
css
.box {
transition: all 1s linear;
}
.box:hover {
width: 400px;
height: 400px;
background-color: #000;
}
鼠标悬停时,方块的宽高和背景色会在 1 秒内匀速变化。
三、关键帧动画(@keyframes)
作用:定义复杂的多阶段动画效果。
核心属性:
animation-name:绑定的关键帧名称。
animation-duration:动画单次时长。
animation-timing-function:动画速度曲线。
animation-iteration-count:动画播放次数,infinite 表示无限循环。
animation-play-state:控制动画状态,paused 可暂停动画。
示例:
css
css
.box {
animation-name: foo;
animation-duration: 2s;
animation-timing-function: linear;
animation-iteration-count: infinite;
}
.box:hover {
animation-play-state: paused;
}
@keyframes foo {
0% { transform: translateX(0); }
50% { transform: translateX(400px); }
100% { transform: translateX(0); }
}
方块会在 0-400px 之间水平往复移动,鼠标悬停时动画暂停。
四、3D 变换
实现基础:父元素需设置 perspective(定义透视距离,模拟人眼到元素的距离)和 transform-style: preserve-3d(让子元素保持 3D 空间)。
常用变换:
rotateY(180deg):沿 Y 轴旋转 180 度。
translateZ(10px):沿 Z 轴向前移动 10px(值越大,元素看起来越近)。
示例:
css
css
body {
perspective: 1000px;
}
.box {
transform-style: preserve-3d;
}
.box:hover .div1 {
transform: rotateY(180deg) translateZ(-10px);
}
.box:hover .div2 {
transform: rotateY(180deg) translateZ(10px);
}
鼠标悬停时,两个子元素会沿 Y 轴旋转并向 Z 轴正反方向移动,形成立体翻转效果。
五、Flex 弹性布局
容器属性
display: flex:将元素设置为弹性容器,子元素默认沿主轴(水平方向)排列。
flex-direction:控制主轴方向,可选值 row(横向,默认)、column(纵向)、row-reverse(横向反转)、column-reverse(纵向反转)。
flex-wrap:控制子元素是否换行,可选值 nowrap(不换行,默认)、wrap(换行)。
justify-content:主轴对齐方式,可选值 flex-start(起点对齐)、flex-end(终点对齐)、center(居中对齐)、space-between(两端对齐)、space-around(分散对齐)。
align-items:交叉轴对齐方式,可选值 stretch(拉伸填充,默认)、flex-start、flex-end、center。
align-content:多行子元素在交叉轴的对齐方式(仅子元素换行时生效)。
子元素属性
order:控制子元素排序,值越小越靠前(默认值为 0)。
flex-grow:子元素的放大比例,会分配容器的剩余空间,值越大占比越多(默认值为 0,即不放大)。
flex-shrink:子元素的缩小比例,当容器空间不足时,值越大缩小幅度越大(默认值为 1,即允许缩小)。