How to center in CSS

Damaris Göbel
1 min readApr 2, 2021

Centering anything in CSS seem to be like a mystery game. I usually write CSS and look at the outcome and at some attempts it works.

First of all, you have to ask yourself what do you want to center?

Center text

In case of text, just write text-align: center

Center a block-level element

Centering more than text, a block or an image

You are setting margin-left and margin-right to auto. It has to have a set width, otherwise it would be full width and wouldn’t need centering.

Center a few block-level elements

For centering a few block-level elements you use the famous flexbox and just give the parent element a display: flex and justify-content: center.

If you would like to position multiple block-level elements under each other you can simply use margin auto and a width.

If you happen to know the height of the element

You can center vertically like with position: relative on the parent element and position absolute on the child element with setting a percentage for top:

Center in both directions, vertically and horizontally

Give the parent element display: flex, justify-content: center and align-items: center to center in both directions

There are actually also more ways of centering elements but let’s keep it simple. Now you have no excuse (or at least me) to not center elements in CSS!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Damaris Göbel
Damaris Göbel

Written by Damaris Göbel

I like to do crazy things with CSS & JavaScript. My brain occasionally runs out of memory so I need to write down my thoughts.

No responses yet

Write a response