translate()

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

语法

``````/* 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%);
``````

值

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

$\left(\begin{array}{cc}10& tx\\ 01& ty\\ 0& 0& 1\end{array}\right)$ $\left(\begin{array}{cc}10& tx\\ 01& ty\\ 0& 0& 1\end{array}\right)$ $\left(\begin{array}{ccc}10& 0& tx\\ 01& 0& ty\\ 0& 0& 1& 0\\ 0& 0& 0& 1\end{array}\right)$
`[1 0 0 1 tx ty]`

形式语法

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

例子

使用单个轴平移

HTML

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

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

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

CSS

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

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

规格

CSS Transforms Level 1
translate()
Working Draft Initial definition