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

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

Remove ads
Remove ads

๐Ÿ“š Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. โ˜•

Get access Support us
Remove ads Read more on
Remove ads
Remove ads
๐ŸŽ‰ Thank you for subscribing to our newsletter. x 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.