Thuộc tính transform cho phép bạn xoay, co giãn, nghiêng, dịch chuyển phần tử trong không gian 2D hoặc 3D. Giá trị là chuỗi các hàm biến đổi: translate(), rotate(), scale(), skew(), matrix() và phiên bản 3D: translate3d(), rotate3d(), perspective()...
Ví dụ minh họa
Mã sau xoay hộp 60 độ khi nhấn nút:
<!DOCTYPE html>
<html>
<head>
<style>
#box {
margin-left: 20px;
border: 2px solid black;
width: 300px;
height: 250px;
background-color: gray;
color: white;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
}
</style>
</head>
<body>
<button onclick="applyTransform()">Áp dụng biến đổi</button>
<div id="box"><p>Demo Text</p></div>
<script>
function applyTransform() {
document.getElementById("box").style.transform = "rotate(60deg)";
/* Các hàm thường dùng:
translate(x, y) | translateX(x) | translateY(y)
rotate(angle) | rotateX(angle) | rotateY(angle) | rotateZ(angle)
scale(x, y) | scaleX(x) | scaleY(y)
skew(x-angle, y-angle) | skewX(angle) | skewY(angle)
matrix(a, b, c, d, e, f) -- 2D matrix
translate3d(x, y, z) | rotate3d(x, y, z, angle) | perspective(length)
*/
}
</script>
</body>
</html>
Các hàm biến đổi phổ biến
| Hàm | Mô tả | Ví dụ |
|---|---|---|
translate(x, y) | Dịch chuyển 2D | translate(50px, 100px) |
translate3d(x, y, z) | Dịch chuyển 3D (kích hoạt GPU) | translate3d(0, 0, 50px) |
rotate(angle) | Xoay 2D (theo trục Z) | rotate(45deg), rotate(-0.5turn) |
rotateX/Y/Z(angle) | Xoay 3D quanh trục X/Y/Z | rotateX(60deg) |
scale(x, y) | Co giãn 2D | scale(1.5), scale(2, 0.5) |
scale3d(x, y, z) | Co giãn 3D | scale3d(1, 1, 2) |
skew(x, y) | Nghiêng 2D | skew(20deg, 10deg) |
perspective(n) | Đặt perspective cho chính phần tử | perspective(500px) |
Lưu ý quan trọng
- Thứ tự quan trọng:
transform: translate(50px) rotate(45deg)khácrotate(45deg) translate(50px). - Transform origin: Mặc định xoay quanh tâm (
50% 50%). DùngtransformOriginđể đổi. - GPU acceleration:
translate3d,translateZ(0)thường kích hoạt compositing layer, mượt hơn cho animation. - Không ảnh hưởng layout: Transform không làm dịch chuyển các phần tử khác (khác với top/left/margin).