r/css 5d ago

What’s Your Go-To Trick for Centering Elements in CSS? Question

I know there are so many ways to center elements in CSS Flexbox, Grid, margin auto, etc. but I always feel like I’m overcomplicating it. What’s your preferred method for centering, and do you have any tips for choosing the best approach in different situations?

8 Upvotes

13

u/ogCITguy 5d ago

css .parent { display: grid; place-content: center; }

21

u/tilr88 5d ago

nothing new, I just define two classes for centering stuff and reuse them:

css .flex-center { display: flex; align-items: center; justify-content: center; } .absolute-center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }

10

u/suspirio 5d ago

alternately:

display: grid; place-content: center;

or

position: absolute; inset: 50%; transform: translate(-50%, -50%);

cheers!

1

u/ddz1507 5d ago

display: grid; place-content: center;

Yes, this.

3

u/bithiba 5d ago
.grid-center {
    display: grid;
    place-items: center;
}

3

u/TheOnceAndFutureDoug 5d ago

display: grid; place-items: center;

I've started defaulting to Grid over Flexbox because you can have all the styling on the parent.

2

u/so-very-very-tired 5d ago

These days flex or grid is usually the easiest.

2

u/Joyride0 5d ago

Flexbox parent, justify-content and align-items center. Text-align center with a defined width.

3

u/bryku 5d ago
.child-center{
    display: grid;
    place-items: center;
}

2

u/CrunchyWeasel 5d ago

Missing some basics here.

display: block;
align-content: center;
text-align: center;

Less chance of content invading your padding with block display than flex display.

2

u/Extension_Anybody150 5d ago

I usually go with flexbox for centering, just set the parent to display: flex, then use justify-content: center and align-items: center. It’s simple and works for most cases. If it’s a fixed-width element, I’ll use margin: auto for horizontal centering, but flexbox is more versatile overall. Grid’s great too but I save it for more complex layouts.

2

u/abrahamguo 5d ago

I just go for margin: auto if applicable (horizontal centering only) since it’s just one property. If not applicable, go to flexbox.

I would say grid is for more complex layouts and isn’t necessary just to center something.

1

u/NiceShotRudyWaltz 5d ago

Margin:auto or wrap it in a flex container and align-items/justify-content:center

1

u/sheriffderek 5d ago

This can’t be answered without context. The idea that there is “a way to center” is part of the problem. It’s almost always something else -

1

u/TheJase 4d ago

align-content: center

That's all you need now

1

u/ahnerd 3d ago

I use flexbox.

0

u/Rarst 5d ago

I have this guide bookmarked and pick from it whatever is appropriate to situation https://css-tricks.com/centering-css-complete-guide/