一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第2天,点击查看活动详情。
在没有设置过transform-origin属性时,CSS变形进行的旋转、移位、缩放等操作都是以元素自己中心点位置进行变形的。CSS中的transform-origin属性用于设置旋转元素的基点位置,熟练使用transform-origin并结合CSS3动画可以使元素沿着某一基点进行旋转,位移等,从而做出特殊的效果。
transform-origin属性值可以是百分比、em、px等具体的值,也可以是top、right、bottom、left和center这样的关键词。
圆周环绕动画
transform-origin: x-axis y-axis z-axis;
默认值:transform-origin:50% 50% 0;
.outer {
/**定义子元素水平居中**/
display: flex;
justify-content: center;
width: 100px;
height: 100px;
background-color: #6a5acd8c;
position: relative;
}
.inner {
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #6a5acdeb;
transform-origin: 50% 50px; /**50px为环绕半径*/
animation: an-circle 3s ease-in-out infinite;
}
@keyframes an-circle {
to {
transform: rotate(1turn);
}
}
transform-origin的第一个参数50%(默认值),表示x轴为小圆原点;第二个参数50px,表示y轴距离小圆原点50px。
加载动画
<div class="outer">
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
</div>
.inner {
position: absolute;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #6a5acdeb;
transform-origin: 50% 50px;
animation: an-circle 3s ease-in-out infinite;
}
.inner:nth-child(2) {
height: 18px;
width: 18px;
animation-delay: 0.2s;
}
.inner:nth-child(3) {
height: 16px;
width: 16px;
animation-delay: 0.4s;
}
.inner:nth-child(4) {
height: 14px;
width: 14px;
animation-delay: 0.6s;
}
@keyframes an-circle {
to {
transform: rotate(1turn);
}
}
transform-origin对scale的作用
.father {
display: flex;
}
.test {
width: 100px;
height: 100px;
background-color: red;
font-size: 20px;
transform: scale(0.5);
transform-origin: 0 0;
}
.box {
width: 100px;
height: 100px;
background-color: antiquewhite;
}
<div class="father">
<div class="test">1212</div>
<div class="box"></div>
</div>
transform-origin:0 0表示以左上角顶点进行缩放。
当我们放大和缩小的时候,并不会改变实际的尺寸,但是显示的时候还是会显示为放大或者缩小后的尺寸,但是并不会挤占周围的空间,也就是缩小后,后面的元素并不会往前移动。
注意:如果在放大的情况下,不设置transform-origin,那么里面的文字就会看不见,这是因为从中心放大,文字跑出屏幕外了。