Centering in CSS has traditionally been a cause for frustration. It’s an everyday task yet there are so many possible solutions! The approach you take will differ depending on whether you’re centering horizontally, vertically or both!

In this tutorial, we’ll look at which methods are best in each scenario.

Horizontal Centering

Inline Elements

Inline elements like text (and links) are super simple to center horizontally using the text-align property:

p {
  text-align: center;
}

This works for inline, inline-block, inline-flex, inline-table, etc.

Block Elements

A block-level element can be centered if both its margin-left and margin-right properties are set to auto (assuming the element has a width). It’s often done with the margin shorthand:

.element {
  margin: 0 auto;
}

However, the modern way to center block level elements (anything that isn’t text) is to use Flexbox!

Let’s assume we have HTML like so:

<div class="container">
  <div>.element</div>
</div>

Add the following CSS:

.container {
  display: flex;
  justify-content: center;
}

This will horizontally center any element inside the .container element.

Horizontal Center

Vertical Centering

Vertical centering has traditionally been quite tricky. And more often than not it’d be accomplished with code like so:

.parent {   
  position: relative; 
} 
.child {   
  position: absolute;   
  top: 50%;   
  transform: translateY(-50%); 
}

This indeed works as it moves the child element back up half the distance of of its height. And it positions the middle of the child element at the middle of its parent.

However, we can do this much more simply with Flexbox:

.container {
  display: flex;
  align-items: center;
}

This will vertically center any element inside the .container element.

Vertical Center

Centering both Vertically and Horizontally

To center both vertically and horizontally we simply combine these techniques!

To perfectly center an element, in the middle of its container:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

Perfect Center

If using CSS Grid, we can also do this easily:

.container {
  display: grid;
  place-items: center;
}

Anything can be centered in CSS!

Once you know the basics of Flexbox and Grid, you’ll see just how simple it is! 👍

Related Posts: