CSS: How to center content (multiple ways)

The Problem

How to make content centered both vertically and horizontally.

The Context

Let’s assume we have simple html structure like this:


<div class="container">
  <div class="content">Look ma, no hands!</div>
</div>

Table way (old way #1)

In this method we’re using CSS to change our divs into tables. That’s why we can use table properties to align the content.


.container {
  display: table;
}
.container .content {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

Absolute-position way (old way #2)

Here we’re using absolute positioning. Instead of negative margins transform property is used. That’s why we don’t need to calculate anything. Also: don’t forget to set relative positioning for parent element!


.container {
  position: relative;
}
.container .content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Flex way (modern way #1)

Simply use new display type – flex – and related properties. More about Flex you can find e.g. on css-tricks.com


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

Grid way (modern way #2)

The same for grid. More on css-tricks.com


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

Working example

You can see live examples on CodePen.