Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Hàm translate() trong CSS - Di chuyển phần tử

Hàm translate() trong CSS dùng để di chuyển phần tử theo hướng ngang và dọc.

Ví dụ 1: Di chuyển ngang 50px

<!DOCTYPE html>
<html>
<head>
<style>
#demo1 { background-color: hsla(140, 100%, 50%, 0.8); }
#demo2 { background-color: hsla(130, 100%, 50%, 0.6); }
.translate_img {
  transform: translate(50px, 0);
}
</style>
</head>
<body>
<h1>Học tập</h1>
<p id="demo1">Excel vlookup</p>
<p id="demo2">Excel filters</p>
<h4>Học Excel</h4>
<img class="translate_img" src="https://www.tutorialspoint.com/videotutorials/assets/videos/courses/42/images/course_42_image.png" alt="MS Excel">
</body>
</html>

Kết quả

Hàm translate() trong CSS - Di chuyển phần tử

Ví dụ 2: Di chuyển ngang 100px, dọc 50%

<!DOCTYPE html>
<html>
<head>
<style>
.translate_img {
  transform: translate(100px, 50%);
}
</style>
</head>
<body>
<h1>Học tập</h1>
<img class="translate_img" src="https://www.tutorialspoint.com/videotutorials/assets/videos/courses/509/images/course_509_image.png" alt="MongoDB">
</body>
</html>

Kết quả

Hàm translate() trong CSS - Di chuyển phần tử

Cú pháp:

transform: translate(tx, ty);
  • tx: Dịch chuyển trục X (bắt buộc)
  • ty: Dịch chuyển trục Y (tùy chọn, mặc định 0)
  • Đơn vị: px, %, em, rem, vw, vh...
  • % tính theo kích thước chính phần tử (khác với top/left tính theo cha)

Có thêm translateX(), translateY(), translateZ(), translate3d().