🎄 Get 50% off from our JavaScript course for the holidays! 🎄
How to Center Elements in CSS With Flexbox

How to Center Elements in CSS With Flexbox

Ferenc Almasi • 2020 August 05 • 📖 1 min read

Using flexbox, it takes only three rules to dead center elements in CSS:

.city {
  display: flex;
  justify-content: center;
  align-items: center;
}
center.css
Copied to clipboard!
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
JavaScript Course

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;
}
center.css
Copied to clipboard!

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%);
}
center.css
Copied to clipboard!

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

JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More

Recommended

🎉 Thank you for subscribing to our newsletter. x