CSS transform: translate()

The CSS translate() function is used to define the transform property to move an element right/left on x-axis and up/down on y-axis, at once. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      div{width: 120px; height: 60px; background: peru; margin: auto;}
      .b{transform: translate(60px, 0px);}
      .c{transform: translate(0px, 60px);}
      .d{transform: translate(40px, 10px);}
      .e{transform: translate(140px, 30px);}
   </style>
</head>
<body>
   
   <h2>Without transform: translate()</h2>
   <div class="a"></div>

   <h2>transform: translate(60px, 0px)</h2>
   <div class="b"></div>

   <h2>transform: translate(0px, 60px)</h2>
   <div class="c"></div>

   <h2>transform: translate(40px, 10px)</h2>
   <div class="d"></div>

   <h2>transform: translate(140px, 30px)</h2>
   <div class="e"></div>
   
</body>
</html>
Output

Without transform: translate()

transform: translate(60px, 0px)

transform: translate(0px, 60px)

transform: translate(40px, 10px)

transform: translate(140px, 30px)

CSS translate() Syntax

The syntax of translate() function in CSS, is:

transform: translate(x, y);

The first parameter, that is the x parameter refers to translateX(), whereas the y parameter refers to translateY(). Therefore, the general form of translate() function can also be written as:

transform: translate(translateX(), translateY());

Note - If we provide single value to translate(), then the value get assigned to translateX(), and the value of translateY() becomes 0 automatically. Therefore, translate(20px) is equal to translate(20px, 0). For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      div {width: 100px; height: 100px; background-color: peru;}

      .a {transform: translate(20px);}
      .b {transform: translate(20px, 0);}
   </style>
</head>
<body>
   
   <h2>translate(20px)</h2>
   <div class="a"></div>

   <h2>translate(20px, 0)</h2>
   <div class="b"></div>
   
</body>
</html>
Output

translate(20px)

translate(20px, 0)

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!