How to Center Text Vertically and Horizontally in CSS
We can align text in the center by simply setting text-align
to center
. But how do you align it vertically? Simply set line-height
to the containerβs height and you are done:
Copied to clipboard! Playground
.container {
background: cornflowerblue;
width: 250px;
height: 250px;
text-align: center;
line-height: 250px;
}
In the example above, the height of the container is set to 250px
so the line-height
should be 250px
as well.
The Modern Solution
If you want to go with a modern and shorter solution, you can also use flexbox, with justify-content
and align-items
:
Copied to clipboard! Playground
.container {
display: flex;
justify-content: center;
align-items: center;
}
justify-content
centers it on the horizontal axisalign-items
centers it along the vertical axis
Resources:
π More Webtips
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:
Courses
CSS - The Complete Guide (including Flexbox, Grid and Sass)
Including Flexbox, Grid, and Sass
Whether you're learning CSS for the first time or brushing up on your CSS skills and diving even deeper, this course is for you. Every web developer has to know CSS.
The HTML & CSS Bootcamp
From Zero to Expert!
This course covers flexbox, CSS grid, animations, responsive design, and much more! You will find tons of exercises & projects inside this course.
The Creative HTML5 & CSS3 Course
Build Awesome Websites
Learn HTML5 and CSS3 by creating three amazing, well-designed and animated websites from scratch.