transform changes how an element is drawn without changing how it takes up space. The most common transform is translate(), which moves it.
<style>
.row { display: flex; gap: 16px; padding: 20px 0; }
.box { width: 80px; height: 80px; background: #d94a00; color: #fff; display: grid; place-items: center; font-weight: bold; }
.moved { transform: translate(30px, 20px); background: #1a5276; }
</style>
<div class="row">
<div class="box">A</div>
<div class="box moved">B</div>
<div class="box">C</div>
</div>
B moved 30px right and 20px down, but A and C did not move to fill its space. Its original place is still reserved, just like with position: relative.
The functions
| Function | Moves |
|---|---|
translate(x, y) | Both directions |
translateX(x) | Left and right |
translateY(y) | Up and down |
Positive X is right, positive Y is down.
Percentages are relative to the element itself
translate(50%, 0) moves an element by half its own width. That is the reason for the centering trick you saw in position: absolute:
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Why not just use top and left?
transform is processed by the graphics card and does not trigger a page re-layout. Animations with it are smoother than animations of top, left or margin.
Great for hover effects
transform: translateY(-4px) on hover is the classic “lift”. See Practical Hover Effects.