Kimkorng / Note / 11 AUG, 2025

How to Center Anything with CSS

How to Center Anything with CSS

Centering something in CSS should be easy. But every developer, at some point, ends up Googling it again. That’s because there are multiple ways to do it, and which one you use depends on what you’re centering.

Let’s keep it simple and cover the most common cases.

1. Center Text Horizontally

For text inside a block element:

css
p { text-align: center; }

That’s it. Works for headings, paragraphs, spans — anything with text.

2. Center a Block Horizontally

If you have a fixed-width block (like a card or image):

css
.card { margin: 0 auto; width: 300px; }

margin: 0 auto; means top and bottom margins are 0, left and right margins are automatic.

3. Center Anything with Flexbox

Flexbox is my go-to because it handles both vertical and horizontal centering.

css
.container { display: flex; justify-content: center; /* horizontal */ align-items: center; /* vertical */ height: 100vh; }

100vh means the container is as tall as the viewport, so the content lands perfectly in the middle.

4. Center with Grid

CSS Grid can also center content in one line:

css
.container { display: grid; place-items: center; height: 100vh; }

place-items: center; is shorthand for aligning both vertically and horizontally.

5. Absolute Centering (Old School)

Before Flexbox and Grid, we used positioning and transform:

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

It still works, but only use it when Flexbox or Grid aren’t an option.

Final Tip

If you can, use Flexbox or Grid — they’re cleaner and easier to maintain. But it’s good to know the old methods because you’ll still run into them in older projects.

Share: