How to Center Elements in CSS With Flexbox
Using flexbox, it takes only three rules to dead center elements in CSS:
.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:
.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
.
.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
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: