Hi Everyone 👋
Today I wanted to share with you how to center text vertically and horizontally in CSS. We will look into three methods to achieve this using CSS Flexbox Layout (Flexible Box) and CSS Grid Layout. Also, in the end, I will show you the easiest way to center text vertically and horizontally.
1. Using CSS Flexbox
We can center text using CSS Flexbox by just these 3 lines of code.
display: flex; align-items: center; justify-content: center;
(Open the Result tab to view the actual output above)
2. Using CSS Grid (Method #1)
We can center text using CSS Grid by just these 3 lines of code.
display: grid; justify-content: center; align-content: center;
3. Using CSS Grid (Method #2) - Easiest way
Now, the easiest way to center text vertically and horizontally when using CSS Grid (method #2) is using just 2 lines of code.
display: grid; place-content: center;
- We can also do this using
display: grid; place-items: center;
So what is the diff between
A: Yes, that is correct but
place-items: center only works for test case #1 & #2 where we have simple text or text inside an element as you can see in this demo:
But in case we have text inside multiple elements like:
<div class="container2 items"> <span>Lorem</span> <span>Lorem</span> <span>Lorem</span> </div>
Then in that case
place-items:center will actually center the text & the element inside each grid row instead of a container, as you can see in the image below.
Btw, I am using the Firefox DevTools CSS Grid Inspector for this image
But, when we use
place-content: center, then grid items are packed flush to each other toward the center of the alignment container as you can see below.
And that is the result we are actually looking for, that's why we have used
place-content: center; instead. I hope that makes sense.
Also, here is the code demo if you want to check it out:
If you prefer watching a video, please check out this video where all the points are explained in full details:
Did you find this article valuable?
Support Palash Mondal by becoming a sponsor. Any amount is appreciated!