Centering in CSS: The Eternal Struggle (and the Trick That Saved Me)

Charis Valtzis

Charis Valtzis

· 2 min read

Every developer has a centering story. You write text-align: center, it works, you feel good. Then you try it on a div and nothing happens. Then margin: auto. Then position: absolute with some numbers you eyeball until it looks right. Then you resize the window and it's off again.

The trick

Early on, a more experienced developer I was working with showed me this:

.element {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

I remember thinking it looked like a hack. It isn't. Once you see why it works, it's actually pretty logical.

Why it works

left: 50% is relative to the parent. It moves the element's left edge to the middle of the container. So now the element starts at the center, which means it's sitting too far to the right.

transform: translateX(-50%) is relative to the element itself. It pulls the element back by half of its own width.

Half of the parent minus half of the element = centered. And because the transform uses the element's own size, you don't need to know the width. It can change and it stays centered.

Same idea on both axes:

.element {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Don't forget the parent needs position: relative (or any non-static position), otherwise the element gets positioned against something further up the page and you're back to square one.

What I actually use today

Honestly, most of the time I don't use the trick above anymore. Flexbox and grid made centering boring, which is a good thing.

Flexbox:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

Grid, which is even shorter:

.container {
  display: grid;
  place-items: center;
}

I still reach for the transform version when the element has to be taken out of the normal flow: a badge on top of an image, a loading spinner over a card, a modal. Anything that's position: absolute anyway.

If you're teaching a junior developer, show them the transform trick even if they'll mostly use grid. Understanding why it works teaches you more about how CSS positioning thinks than any one-liner does.

#Centering#Layout#Tips
← All postsHave a project in mind? Let's talk