translate()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

translate() 这个 CSS 函数在水平和/或垂直方向上重新定位元素。其结果是 类型。

尝试一下

transform: translate(0);
transform: translate(42px, 18px);
transform: translate(-2.1rem, -2ex);
transform: translate(3ch, 3mm);
#static-element {
  opacity: 0.4;
  position: absolute;
}

#example-element {
  position: absolute;
}

该变换由二维向量构成。它的坐标定义了元素在每个方向上移动了多少。

语法

css
/* Single  values */
transform: translate(200px);
transform: translate(50%);

/* Double  values */
transform: translate(100px, 200px);
transform: translate(100px, 50%);
transform: translate(30%, 200px);
transform: translate(30%, 50%);

单个 作为参数

该值是 或者 代表翻译向量的横坐标 (horizontal, x-coordinate) . 而向量的纵坐标 (vertical, y-coordinate) 会被默认为 0. 例如,translate(2) 等价于 translate(2, 0) 。里面还可以填百分比值,百分比值是指 transform-box 属性定义的参考框的宽度。

参数是两个 构成

此值描述两个 值,分别代表翻译的横坐标 (x-coordinate) 和纵坐标 (y-coordinate) 向量。百分比作为第一个值表示宽度,第二个部分表示由 transform-box 属性定义的参考框的高度。

Cartesian coordinates on ℝ2 Homogeneous coordinates on ℝℙ2 Cartesian coordinates on ℝ3 Homogeneous coordinates on ℝℙ3

平移不是 ℝ2 中的线性变换,因此不能使用矩阵来表示。

10tx01ty001 10tx01ty001 100tx010ty00100001
[1 0 0 1 tx ty]

形式语法

css
translate(, ?)

示例

使用单个轴平移

HTML

html
Static
Moved
Static

CSS

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

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

结果

y 轴和 x 轴都平移

HTML

html
Static
Moved
Static

CSS

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

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

结果

规范

Specification
CSS Transforms Module Level 1
# funcdef-transform-translate

浏览器兼容性

参见