
How to Center Elements in CSS With Flexbox
Using flexbox, it takes only three rules to dead center elements in CSS:
Copied to clipboard! Playground
.city {
display: flex;
justify-content: center;
align-items: center;
}
justify-content
centers it on the horizontal axisalign-items
centers it along the vertical axis
Don't Want to Use Flexbox?
There are several other ways to dead center elements. If you need to center a text vertically, you can do it by setting the line-height
to the height of its container:
Copied to clipboard! Playground
.container {
background: cornflowerblue;
width: 250px;
height: 250px;
text-align: center;
/* set line-height to the height of the container */
line-height: 250px;
}
You can also easily center absolutely positioned elements by using transform
.
Copied to clipboard! Playground
.center {
top: 50%;
left: 50%;
/**
* This will move the element -50%
* It will also move it -50% to the top
**/
transform: translate(-50%, -50%);
}
By default, anchor points are set to the top-left corner of an element. To dead center absolutely positioned elements, you need to move them back -50% on both axis. Think of it as setting an anchor point to the center.

Resource
π More Webtips
Master the Art of Frontend
Access exclusive interactive lessons
Unlimited access to hundreds of tutorials
Remove ads to learn without distractions
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.