translateX()

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.

Hàm translateX() CSS function định vị lại một phần tử theo chiều ngang trên mặt phẳng 2D. Kết quả của nó là kiểu dữ liệu <transform-function>.

Try it

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;
}

Note: translateX(tx) tương đương với translate(tx, 0) hoặc translate3d(tx, 0, 0).

Cú pháp

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

Giá trị

<length-percentage>

Là một <length> hoặc <percentage> biểu thị hoành độ (ngang, thành phần x) của vector dịch chuyển [tx, 0]. Trong hệ tọa độ Descartes, nó biểu thị độ dịch chuyển dọc theo trục x. Giá trị phần trăm tham chiếu đến chiều rộng của hộp tham chiếu được xác định bởi thuộc tính transform-box.

Tọa độ Descartes trên ℝ^2 Tọa độ thuần nhất trên ℝℙ^2 Tọa độ Descartes trên ℝ^3 Tọa độ thuần nhất trên ℝℙ^3

Phép dịch chuyển không phải là phép biến đổi tuyến tính trong ℝ^2 và không thể biểu diễn bằng ma trận tọa độ Descartes.

(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]

Cú pháp chính thức

<translateX()> = 
translateX( <length-percentage> )

<length-percentage> =
<length> |
<percentage>

Ví dụ

HTML

html
<div>Tĩnh</div>
<div class="moved">Đã di chuyển</div>
<div>Tĩnh</div>

CSS

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

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

Kết quả

Thông số kỹ thuật

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

Khả năng tương thích trình duyệt

Xem thêm