DEV Community

Cover image for Centering vertically and horizontally with CSS

Centering vertically and horizontally with CSS

Alvaro Montoro on January 07, 2022

This article will show five different ways of centering vertically and horizontally with HTML+CSS, presented in chronological order: from how it wa...
Collapse
 
alohci profile image
Nicholas Stimpson

I am a developer. and I like a couple of methods not mentioned here.

Collapse
 
alvaromontoro profile image
Alvaro Montoro

Nice. Which ones? line-height equal to height? display: flex in the container and margin:auto auto? There are a few.

Collapse
 
alohci profile image
Nicholas Stimpson • Edited

Indeed there are. While like everyone else I use display:flex these days, it's wise to know the options:

  1. CSS tables. So you don't need to use HTML table/tr/td. A display:table container and a display:table-cell child is sufficient, and doesn't violate HTML semantics.

  2. position:absolute; top:0; bottom:0; left:0; right:0; margin:auto; height:fit-content; width:fit-content; in a position:relative container.

  3. vertical align:middle on an inline-block element aligned to a single line, inline-block, middle aligned pseudo-element with height:100%;

Thread Thread
 
afif profile image
Temani Afif

yes the (2) which now can be simplified using inset:0 ;)

Collapse
 
joshuacba08 profile image
Josué Oroya

so could you mention those methods?

Collapse
 
alvaromontoro profile image
Alvaro Montoro

There was a follow up comment with three methods: dev.to/alohci/comment/1l4c4

And Temani Afif added an alternative.

Collapse
 
grahamthedev profile image
GrahamTheDev

Did you, did you just do a post on centring a div?

I was told that this is a skill developers cannot learn!

Collapse
 
alvaromontoro profile image
Alvaro Montoro

I'm not a developer, so we are ok ;)

Collapse
 
alvaromontoro profile image
Alvaro Montoro • Edited

I'm confused (and curious) about why people are liking this comment 🤔😅

Thread Thread
 
grahamthedev profile image
GrahamTheDev

Time to post a “10 JS one liners” post to prove that you are! 🤣

Thread Thread
 
alvaromontoro profile image
Alvaro Montoro

I'm going to publish a book: "100 tips to become a 100x Engineer".
100¢ now, $100 later! Take advantage of this amazing offer in the next 100 seconds!

Collapse
 
dalcio profile image
Dalcio • Edited

Who place-items show. I was looking for this rule dude

div {
    height: 100vh;
    display: flex;
    place-items: center;
    place-content: center;
}
Enter fullscreen mode Exit fullscreen mode

Note flex and grid containers must have a height to be possible center the elements vertical

Collapse
 
marcselman profile image
Marc Selman • Edited

Technically place-items is a shorthand for align-items and justify-items. Not for align-items and justify-content. But for centering a single div that doesn't matter much.

Collapse
 
shivamkumarsah profile image
Shivam Kumar Sah

I use flex everytime to position an element