Centring the item with two lines of code

joannaotmianowska

Joanna Otmianowska

Posted on April 20, 2021

Centring the item with two lines of code

Do you remember centring the item on the screen horizontally and vertically the old way? Before flexbox and CSS grid that was really hard to do it. I usually either relied on the numbers (so defining margin or padding for the item - which is not good idea cause it looks different on different screens) or used floating. There was also a way with creating tables and putting your content there. I won't give any examples in code here not to misguide anyone looking for the solution to that. These old ways are really outdated.

When flexbox came around couple years ago it was like a miracle. Finally being able to center the item with three lines of CSS code felt like a dream to me. It was simple:

  display: flex;
  justify-content: center;
  align-items: center;
Enter fullscreen mode Exit fullscreen mode

I used this way very often. Till recently when I discovered simplest way thanks to Chris' Ferdinandi Daily Developer Tips.

Brace yourself, here it comes:

  display: grid;
  place-content: center;
Enter fullscreen mode Exit fullscreen mode

That's it. Isn't it awesome? I found it on this site that Chris shared. That's a really cool project done by Stephanie Eckles. She shares short and simple CSS code snippets. I highly recommend to check it out.

💖 💪 🙅 🚩
joannaotmianowska
Joanna Otmianowska

Posted on April 20, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related