translate3d()

Baseline 已廣泛支援

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

translate3d() CSS 函式在 3D 空間中重新定位元素。其結果是一個 <transform-function> 資料型別。

試一試

transform: translate3d(0, 0, 0);
transform: translate3d(42px, -62px, -135px);
transform: translate3d(-2.7rem, 0, 1rem);
transform: translate3d(5ch, 0.4in, 5em);
<section class="default-example" id="default-example">
  <div class="transition-all" id="example-element">
    <div class="face front">1</div>
    <div class="face back">2</div>
    <div class="face right">3</div>
    <div class="face left">4</div>
    <div class="face top">5</div>
    <div class="face bottom">6</div>
  </div>
</section>
#default-example {
  background: linear-gradient(skyblue, khaki);
  perspective: 800px;
  perspective-origin: 150% 150%;
}

#example-element {
  width: 100px;
  height: 100px;
  perspective: 550px;
  transform-style: preserve-3d;
}

.face {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  position: absolute;
  backface-visibility: inherit;
  font-size: 60px;
  color: white;
}

.front {
  background: rgb(90 90 90 / 0.7);
  transform: translateZ(50px);
}

.back {
  background: rgb(0 210 0 / 0.7);
  transform: rotateY(180deg) translateZ(50px);
}

.right {
  background: rgb(210 0 0 / 0.7);
  transform: rotateY(90deg) translateZ(50px);
}

.left {
  background: rgb(0 0 210 / 0.7);
  transform: rotateY(-90deg) translateZ(50px);
}

.top {
  background: rgb(210 210 0 / 0.7);
  transform: rotateX(90deg) translateZ(50px);
}

.bottom {
  background: rgb(210 0 210 / 0.7);
  transform: rotateX(-90deg) translateZ(50px);
}

此變換由三維向量 [tx, ty, tz] 表徵。其座標定義了元素在每個方向上移動的量。

語法

css
translate3d(tx, ty, tz)

tx

<length><percentage>,表示平移向量 [tx, ty, tz] 的橫座標(水平,x 分量)。

ty

<length><percentage>,表示平移向量 [tx, ty, tz] 的縱座標(垂直,y 分量)。

tz

<length>,表示平移向量的 z 分量。它不能是 <percentage> 值;在這種情況下,包含該轉換的屬性被認為是無效的 [tx, ty, tz]。

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

此變換適用於 3D 空間,無法在平面上表示。

平移不是 ℝ^3 中的線性變換,不能用笛卡爾座標矩陣表示。
(100tx010ty001tz0001)\left( \begin{array}{cccc} 1 & 0 & 0 & tx \\ 0 & 1 & 0 & ty \\ 0 & 0 & 1 & tz \\ 0 & 0 & 0 & 1 \end{array} \right)

正式語法

<translate3d()> = 
translate3d( <length-percentage> , <length-percentage> , <length> )

<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 {
  /* Equivalent to perspective(500px) translateX(10px) */
  transform: perspective(500px) translate3d(10px, 0, 0px);
  background-color: pink;
}

結果

結合 z 軸和 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: perspective(500px) translate3d(10px, 0, 100px);
  background-color: pink;
}

結果

規範

規範
CSS 變換模組級別 2
# funcdef-translate3d

瀏覽器相容性

另見