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

浏览器兼容性

另见