translateX()

Baseline 已廣泛支援

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

translateX() CSS 函式在2D平面上水平重新定位元素。它的結果是<transform-function>資料型別。

試一試

transform: translateX(0);
transform: translateX(42px);
transform: translateX(-2.1rem);
transform: translateX(3ch);
<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;
}

注意: translateX(tx) 等同於 translate(tx, 0)translate3d(tx, 0, 0)

語法

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

<length-percentage>

<length><percentage>,表示平移向量 [tx, 0] 的橫座標(水平,x分量)。在笛卡爾座標系中,它表示沿x軸的偏移。百分比值是相對於由transform-box屬性定義的參考框的寬度。

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

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

(10t010001)\left( \begin{array}{ccc} 1 & 0 & t \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{array} \right)
(10t010001)\left( \begin{array}{ccc} 1 & 0 & t \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{array} \right)
(100t010000100001)\left( \begin{array}{cccc} 1 & 0 & 0 & t \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{array} \right)
[1 0 0 1 t 0]

正式語法

<translateX()> = 
translateX( <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 {
  transform: translateX(10px); /* Equal to translate(10px) */
  background-color: pink;
}

結果

規範

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

瀏覽器相容性

另見