預設情況下,CSS 變形的原點落在元素的正中央,也就是 X 軸與 Y 軸的 50% 處。所以我們做 rotate、scale、translate 時,元素總是繞著自己的中心轉。
但很多時候我們需要繞著別的地方轉——例如讓時鐘指針繞著尾端旋轉,或讓卡片從左下角翻開。這時候就要用 transform-origin 改寫原點。把值設為 0 0,原點就跳到元素的左上角。
語法
transform-origin: [<percentage> | <length> | left | center | right | top | bottom];
取值可以是百分比、em、px 等具體數值,也可以是 top、right、bottom、left、center 這些關鍵字。
2D 變形時可以給一個或兩個值:兩個值時,第一個設水平 X 軸位置,第二個設垂直 Y 軸位置。3D 變形則多了第三個 Z 軸值。
各參數說明
- x-offset:水平偏移量,可用 length 或 percentage。正值向右,負值向左。
- offset-keyword:top、right、bottom、left、center 之一。
- y-offset:垂直偏移量,正值向下,負值向上。
- x-offset-keyword:left、right 或 center。
- y-offset-keyword:top、bottom 或 center。
- z-offset:3D 變形中遠離視點的距離,預設 0,只接受 length,百分比在此無效。
關鍵字與百分比對照表
transform-origin 的取值邏輯和 background-position 幾乎一樣,把兩邊對照起來記最有效率:
- top = top center = center top = 50% 0
- right = right center = center right = 100% 50%
- bottom = bottom center = center bottom = 50% 100%
- left = left center = center left = 0 50%
- center = center center = 50% 50%
- top left = left top = 0 0
- right top = top right = 100% 0
- bottom right = right bottom = 100% 100%
- bottom left = left bottom = 0 100%
記住這組對照,之後不管是做轉盤指針、折頁動畫還是從邊角生長的進度條,都能精準控制旋轉中心。