CodeBlanks Logo Icon CodeBlanks

Translate

CSS course · Intermediate · Lesson 65/98

Learn to move elements with translate().

The translate() function

translate() shifts an element along the X and Y axes. It takes two values: translate(20px, 30px) moves it 20 pixels right and 30 pixels down.

With a single value Y is treated as zero: translate(20px) only shifts right. Handy when you want a one-axis move.

translateX and translateY

To change one axis only, use translateX() or translateY(). translateX(-10px) shifts 10 pixels left; translateY(15px) shifts 15 pixels down.

These functions help readability: at a glance you see which axis is moving. Choosing a single axis over two-value translate() often gives a cleaner line.

translate with percentages

You can write a percentage instead of pixels. The percentage is based on the element's own size, not the container. translateX(50%) shifts the element by half its own width to the right.

That is handy for centring: with translate(-50%, -50%) you can place the exact middle of an absolutely positioned element on a point.

Exercise Hover-driven slide

Add two style blocks. First a .card selector with transform: translateX(0). Second a .card:hover selector with transform: translateX(12px). The card should slide right on hover.

Show example solution
/* add a transform for the card */
.card {
  transform: translateX(0);
}
.card:hover {
  transform: translateX(12px);
}

Test yourself

  1. What does translate(20px, 30px) do?

    .arrow {
      transform: translate(20px, 30px);
    }
    • Shifts 20 pixels right, 30 pixels down
    • Shifts 20 pixels up, 30 pixels left
    • Grows 20 pixels, shrinks 30 pixels
    • Rotates 20 degrees right, 30 degrees down
    Show answer

    Shifts 20 pixels right, 30 pixels down — Correct. The first value is the X axis (20 pixels right), the second is the Y axis (30 pixels down).

  2. Write the translateX function

    .arrow {
      transform: ____(15px);
    }
    Show answer
    .arrow {
      transform: translateX(15px);
    }
  3. Match each function to its motion

    translateX(10px)
    10 pixels right
    translateY(-5px)
    5 pixels up
    translate(0, 20px)
    20 pixels down
    translate(-10px, 0)
    10 pixels left

All lessons in Intermediate