Thuộc tính transformOrigin xác định điểm gốc (trục quay, tâm co giãn) cho các biến đổi transform. Mặc định là 50% 50% (trung tâm). Bạn có thể đặt bằng từ khóa, phần trăm, hoặc độ dài.
Ví dụ minh họa
Mã sau đặt perspectiveOrigin trên container và transformOrigin trên div con khi nhấn nút:
<!DOCTYPE html>
<html>
<head>
<style>
#div1 {
position: relative;
margin: auto;
height: 200px;
width: 200px;
padding: 20px;
border: 2px solid blue;
perspective: 100px;
}
#div2 {
padding: 80px;
position: absolute;
border: 2px solid blue;
background-color: yellow;
transform: rotateX(45deg);
}
#div3 {
padding: 50px;
position: absolute;
border: 2px solid blue;
background-color: green;
transform: rotateX(30deg);
}
</style>
</head>
<body>
<p>Thay đổi gốc biến đổi</p>
<button onclick="setOrigins()">Đặt Perspective Origin & Transform Origin</button>
<div id="div1">DIV1
<div id="div2">DIV2</div>
<div id="div3">DIV3</div>
</div>
<script>
function setOrigins() {
// Điểm nhìn (vanishing point) cho perspective trên container
document.getElementById("div1").style.perspectiveOrigin = "20px 10%";
// Trục xoay cho div2 (góc trên-trái)
document.getElementById("div2").style.transformOrigin = "0 0";
/* transformOrigin: x y z
x: left/center/right/%/length
y: top/center/bottom/%/length
z: length (mặc định 0) */
}
</script>
</body>
</html>
Cú pháp transformOrigin
transformOrigin: x-axis y-axis z-axis?
- x-axis:
left|center|right|<percentage>|<length> - y-axis:
top|center|bottom|<percentage>|<length> - z-axis:
<length>(mặc định 0)
Ví dụ thường dùng
| Giá trị | Vị trí gốc |
|---|---|
"0 0" hoặc "left top" | Góc trên-trái |
"100% 0" hoặc "right top" | Góc trên-phải |
"0 100%" hoặc "left bottom" | Góc dưới-trái |
"100% 100%" hoặc "right bottom" | Góc dưới-phải |
"50% 50%" hoặc "center center" | Trung tâm (mặc định) |
"50% 0" | Trung tâm cạnh trên |
Mối quan hệ:
perspectiveOrigin: Đặt trên **phần tử cha** (container cóperspective), quyết định vị trí "mắt nhìn".transformOrigin: Đặt trên **phần tử con** (được transform), quyết định "trục xoay/tâm co giãn".