transform 属性可以旋转、缩放、倾斜或平移元素。

<div class="box">三眼鸭的编程教室</div>
<style>
    .box {
        display: inline-block;
        padding: 10px 20px;
        border: 4px solid black;
        transform: translate(30px, 20px) rotate(20deg);
    }
</style>

$$demo

<div class="box">三眼鸭的编程教室</div>

<style> body{min-height: 100px;}

.box {

display: inline-block;

padding: 10px 20px;

border: 4px solid black;

transform: translate(30px, 20px) rotate(20deg);

}

</style>

$$

常用的有以下取值类型,多个取值类型可以共同作用:

  • translate:平移。
  • scale:缩放。
  • rotate:旋转
  • skew:拉伸

$$tip

完整的取值类型参考 transform-function - MDN

$$

平移

translate 定义了元素的平移,也可以拆分成 translateX(水平轴平移)、 translateY (垂直轴平移)。

<iframe height="300" style="width: 100%" scrolling="no" title="演示" src="https://codepen.io/3yya/embed/bGaexqp?default-tab=css%2Cresult&editable=true&theme-id=light" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"></iframe>

缩放

scale 定义了元素的缩放,同样可以拆分成 scaleX (水平缩放)、 scaleY(垂直缩放)。

<iframe height="300" style="width: 100%" scrolling="no" title="演示" src="https://codepen.io/3yya/embed/RwxRYLX?default-tab=css%2Cresult&editable=true&theme-id=light" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"></iframe>

旋转

rotate 定义了元素的旋转角度,取值是角度单位

<iframe height="300" style="width: 100%" scrolling="no" title="演示" src="https://codepen.io/3yya/embed/ZEvOmQY?default-tab=css%2Cresult&editable=true&theme-id=light" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"></iframe>

翻转

rotateX 定义了围绕水平轴的翻转, rotateY 定义了围绕垂直轴的翻转, rotateZ 定义了围绕着纵深轴的翻转(效果等同于 rotate)。

image

<iframe height="300" style="width: 100%" scrolling="no" title="演示" src="https://codepen.io/3yya/embed/GRyqwNG?default-tab=css%2Cresult&editable=true&theme-id=light" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"></iframe>

拉伸

skew 定义了元素的拉伸, skewX 定义水平拉伸,skewY 定义垂直拉伸,取值是角度单位

<iframe height="300" style="width: 100%" scrolling="no" title="演示" src="https://codepen.io/3yya/embed/BaJzGrb?default-tab=css%2Cresult&editable=true&theme-id=light" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"></iframe>


练习

  1. 完成以下实例的效果。

$$demo

<div class="box">三眼鸭的编程教室</div> <style> body{min-height: 200px;} .box { display: inline-block; padding: 10px 20px; border: 4px solid black; transform: translate(120px, 50px) skew(30deg, 20deg); } </style>

$$

$$answer

<div class="box">三眼鸭的编程教室</div>
<style>
    .box {
        display: inline-block;
        padding: 10px 20px;
        border: 4px solid black;
        transform: translate(120px, 50px) skew(30deg, 20deg);
    }
</style>

$$