Centering Things in CSS Using Flexbox

Centering of elements on a page, especially vertical centering, has been notoriously difficult to do in the past with CSS and we’ve had to resolve to a number of hacks. Thankfully though, Flexbox makes it all easier, and we can now instead focus our designing energy towards higher level problems.

The following is a very simple guide on centering elements using Flexbox.

Horizontal Centering

Let’s start with a div that contains two paragraphs that we want to center horizontally on the same axis. It’s as easy as using the justify-content property with a value of center on the container:

Example image arrr!

Example image 2 yeehaw!

<div class="box flex">
  <p>
    <img src="/images/pirate.svg" width="75">
    arrr!
  </p>
  <p>
    <img src="/images/cowboy.svg" width="75">
    yeehaw!
  </p>
</div>
.box.flex {
  display: flex;
  justify-content: center;
}

.box {
  padding: .5rem;
  height: 300px;
  box-shadow: 2px 2px 5px rgba(0,0,0,0.03);
  border-radius: 4px;

  color: #84613D;
  font-family: "Lucida Console", Monaco, monospace;
  background: #FDF9EA;
  border-bottom: 1px solid #F9F2D6;
  border-right: 1px solid #F9F2D6;
}

.box p {
  max-width: 125px;
  text-align: center;
  background: rgba(255,255,255,0.5);
  margin: .25rem;
  padding: .25rem;
}

Vertical Centering

The power of Flexbox really shines when we also need to center elements vertically. Here’s our example, but with the flex items also centered vertically:

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

Example image arrr!

Example image yeehaw!

If you just want specific flex items to be centered vertically, you can set align-self on the items instead:

.flex p:last-child {
  align-self: center;
}

Example image arrr!

Example image yeehaw!

Vertical Centering On Whole Page

If you want to put an element at the dead center of a page, it can be a little bit more tricky because flex items will only center vertically according to the height of their container. That means that the container itself needs to be the same height as the page itself. That easy-enough to do using viewport units, where 100vh is 100% of the height of the viewport.

Here’s a simple example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Dead center!</title>
    <style>
      body {
        margin: 0;
      }

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

        height: 100vh;
      }
    </style>
  </head>
  <body>

    <div class="center-me">
      <p>😇 Bonjour center!</p>
    </div>

  </body>
</html>

Notice also that we make sure to reset the page's margin to 0, as otherwise you'd end up with a little bit of a scroll.

  Tweet It
✖ Clear

🕵 Search Results

🔎 Searching...