Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Các hàm biến đổi 2D (2D Transform Functions) trong CSS


CSS 2D Transform cho phép biến đổi element trên mặt phẳng 2D: di chuyển, xoay, scale, nghiêng.

4 hàm chính

HàmMô tảVí dụ
translate(x, y)Di chuyển theo trục X, Ytranslate(30px, 20px)
scale(x, y)Phóng to/thu nhỏ theo X, Yscale(2, 1.5)
rotate(deg)Xoay theo độ (deg)rotate(45deg)
skew(x, y)Nghiêng theo góc X, Yskew(20deg, 10deg)

Ví dụ

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    div {
      width: 100px;
      height: 100px;
      background-color: rgb(255, 0, 128);
      border: 2px solid rgb(0, 35, 150);
      margin: 20px;
      display: inline-block;
      color: white;
      font-weight: bold;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .rotate { transform: rotate(20deg); }
    .translate { transform: translate(30px, 20px); }
    .scale { transform: scale(2, 1); margin-left: 70px; }
    .skew { transform: skew(20deg); }
  </style>
</head>
<body>
  <h1>Ví Dụ 2D Transform Functions</h1>
  <div class="rotate">ROTATE(20deg)</div>
  <div class="skew">SKEW(20deg)</div>
  <div class="scale">SCALE(2,1)</div>
  <div class="translate">TRANSLATE(30,20)</div>
</body>
</html>

Kết quả

4 hộp hồng: xoay 20°, dịch chuyển 30px phải 20px xuống, phóng to gấp 2 theo chiều ngang, nghiêng 20°.

Kết hợp nhiều transform

transform: translate(50px, 50px) rotate(45deg) scale(1.5);

Thứ tự thực hiện: từ phải sang trái (scale → rotate → translate).