每個元素都有一個中心原點,預設位於 X 軸與 Y 軸的 50% 處,也就是正中央。CSS3 的位移、縮放、旋轉、傾斜,預設全都以這個點為基準。
如果你想讓變形繞著別的位置進行,就得用 transform-origin 把原點搬走。
語法:
transform-origin:取值;
說明:
取值有兩種形式:長度值與關鍵字。長度值通常以百分比表示,用 px 或 em 的情況較少。不論採哪種寫法,都要同時給出水平與垂直兩個方向的值。它的取值邏輯與 background-position 相當接近,可以對照理解。
| 關鍵字 | 百分比 | 說明 |
|---|---|---|
| top left | 0 0 | 左上 |
| top center | 50% 0 | 靠上居中 |
| top right | 100% 0 | 右上 |
| left center | 0 50% | 靠左居中 |
| center center | 50% 50% | 正中 |
| right center | 100% 50% | 靠右居中 |
| bottom left | 0 100% | 左下 |
| bottom center | 50% 100% | 靠下居中 |
| bottom right | 100% 100% | 右下 |
舉例:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>CSS3中心原點transform-origin屬性</title>
<style type="text/css">
/*設置原始元素樣式*/
#origin {
margin:100px auto;
/*水平居中*/
width:200px;
height:100px;
border:1px dashed gray;
}
#current {
width:200px;
height:100px;
color:white;
background-color: #3EDFF4;
text-align:center;
transform-origin:right center;
-webkit-transform-origin:right center;
/*兼容-webkit-引擎浏覽器*/
-moz-transform-origin:right center;
/*兼容-moz-引擎浏覽器*/
transform:rotate(30deg);
-webkit-transform:rotate(30deg);
/*兼容-webkit-引擎浏覽器*/
-moz-transform:rotate(30deg);
/*兼容-moz-引擎浏覽器*/
}
</style>
</head>
<body>
<div id="origin">
<div id="current"></div>
</div>
</body>
</html>
分析:
「transform-origin:right center;」把變形原點從正中央改到靠右居中,於是方塊旋轉時是繞著右側中點轉,而不是原地打轉。虛線框標示的是元素原始位置,方便對照旋轉前後的差異。