πŸ’‘ This page contain affiliate links. By making a purchase through them, we may earn a commission at no extra cost to you.
How to Center Elements in CSS With Flexbox

How to Center Elements in CSS With Flexbox

Ferenc Almasi β€’ 2020 August 05 β€’ Read time 1 min read
  • twitter
  • facebook
CSS

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;
}
center.css
  • justify-content centers it on the horizontal axis
  • align-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;
}
center.css

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%);
}
center.css

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.

How to Center Elements in CSS With Flexbox
If you would like to see more Webtips, follow @flowforfrank

Resource

  • twitter
  • facebook
CSS
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.