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;
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;
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.
Top comments (19)
in a container with
position: relative
you can also use:But yeah, the grid solution is much better
I don't know with trick with
transform
but as mentioned in comments, it looks like a hack before flex era :) Still, very interesting!Isn't it this mentioned "old way"?
Just out of curiosity
the post didn't mention the
transform: translate(x%)
trick but other (even older) ways:ps: I still use the
transform
trick sometimes :)I also sometimes do :) I was just wondering, thanks for claryfing :D
This is 100% the old way. Pre-flexbox that was one of the only ways to do it reasonably well.
Thanks! Thought so. So it was actually mentioned in the article, that this way using grid is the alternative to the old ways.
Hmm but you can't make them vertically center, until unless you define the height for the element,
It's common for both flex and grid templates, but for postion we won't need it, as by default it takes entire screen width and height, until unless we provide the parent tag with a
position: relative;
Nice
thanks!
Yes, that's true. But I guess first version with flex would work here so setting both
align-items
andjustify-content
to center, what do you think?This will add some definite. However there could be more css needed to align multiple items vertically inside the same div. This wouldn't be a difficult, but still requires some more code.
You're right, I didn't noticed that you mentioned vertical centring. That would require more work than 3 lines indeed
Very nice, lol, I was not expecting that — and thanks for that site you linked!
*Edit: I'm cracking up over "Smol" CSS xD
Thanks! Yes, Smol CSS site is awesome :)
Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more