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;
Demo:
(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;
Demo:
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;
Demo:
Questions
- We can also do this using
display: grid;
place-items: center;
So what is the diff between place-items
and place-content
?
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:
Demo
Code
Wrap Up
I hope you will find this video useful and learn something new in the process. If you want to learn more HTML, CSS, JavaScript and web development tips & tricks, please make sure to subscribe on YouTube.
Happy Coding!