translate()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

translate() CSS 函式用於在水平和/或垂直方向上重新定位元素。其結果是一種 <transform-function> 資料型別。

試一試

transform: translate(0);
transform: translate(42px, 18px);
transform: translate(-2.1rem, -2ex);
transform: translate(3ch, 3mm);
<section id="default-example">
  <img
    class="transition-all"
    id="static-element"
    src="/shared-assets/images/examples/firefox-logo.svg"
    width="200" />
  <img
    class="transition-all"
    id="example-element"
    src="/shared-assets/images/examples/firefox-logo.svg"
    width="200" />
</section>
#static-element {
  opacity: 0.4;
  position: absolute;
}

#example-element {
  position: absolute;
}

此變換由一個二維向量 [tx, ty] 表示。其座標定義了元素在每個方向上移動的距離。

語法

css
/* Single <length-percentage> values */
transform: translate(200px);
transform: translate(50%);

/* Double <length-percentage> values */
transform: translate(100px, 200px);
transform: translate(100px, 50%);
transform: translate(30%, 200px);
transform: translate(30%, 50%);

單個 <length-percentage>

此值是一個 <length><percentage>,表示平移向量 [tx, 0] 的橫座標(水平,x 分量)。平移向量的縱座標(垂直,y 分量)將設定為 0。例如,translate(2px) 等同於 translate(2px, 0)。百分比值是指由 transform-box 屬性定義的參考框的寬度。

<length-percentage>

此值描述了兩個 <length><percentage> 值,分別表示平移向量 [tx, ty] 的橫座標(水平,x 分量)和縱座標(垂直,y 分量)。作為第一個值的百分比是指由 transform-box 屬性定義的參考框的寬度,作為第二個值的百分比是指其高度。

笛卡爾座標,在 ℝ^2 齊次座標,在 ℝℙ^2 笛卡爾座標,在 ℝ^3 齊次座標,在 ℝℙ^3

平移不是 ℝ^2 中的線性變換,無法使用笛卡爾座標矩陣表示。

(10tx01ty001)\left( \begin{array}{ccc} 1 & 0 & tx \\ 0 & 1 & ty \\ 0 & 0 & 1 \end{array} \right)
(10tx01ty001)\left( \begin{array}{ccc} 1 & 0 & tx \\ 0 & 1 & ty \\ 0 & 0 & 1 \end{array} \right)
(100tx010ty00100001)\left( \begin{array}{cccc} 1 & 0 & 0 & tx \\ 0 & 1 & 0 & ty \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{array} \right)
[1 0 0 1 tx ty]

正式語法

<translate()> = 
translate( <length-percentage> , <length-percentage>? )

<length-percentage> =
<length> |
<percentage>

示例

使用單軸平移

HTML

html
<div>Static</div>
<div class="moved">Moved</div>
<div>Static</div>

CSS

css
div {
  width: 60px;
  height: 60px;
  background-color: skyblue;
}

.moved {
  /* Equal to: translateX(10px) or translate(10px, 0) */
  transform: translate(10px);
  background-color: pink;
}

結果

結合 y 軸和 x 軸平移

HTML

html
<div>Static</div>
<div class="moved">Moved</div>
<div>Static</div>

CSS

css
div {
  width: 60px;
  height: 60px;
  background-color: skyblue;
}

.moved {
  transform: translate(10px, 10px);
  background-color: pink;
}

結果

規範

規範
CSS 變換模組級別 1
# funcdef-transform-translate

瀏覽器相容性

另見