Helping you build a better website
(and other interesting web stuff)

CSSHTMLJavaScriptjQueryMSSQLMySQLPHPTechnologiesWordpress
Silva Web Designs - Blog

Flex – Vertical Centering

Need a good method to vertical centre elements, then look no further, flex is the way!

There are other techniques that do work for vertical centring such as using table and table-cell with the good old vertical-align: middle, but they never seem to work when you need them.

The current landscape of vertical centring options ranges from negative margins to display:table-cell to ridiculous hacks involving full-height pseudo-elements. Yet even though these techniques sometimes get the job done, they don’t work in every situation. What if the thing you want to centre is of unknown dimensions and isn’t the only child of its parent? What if you could use the pseudo-element hack, but you need those pseudo-elements for something else?

With Flexbox, you can stop worrying. You can align anything (vertically or horizontally) quite painlessly with the align-items, align-self, and justify-content properties.

Unlike some of the existing vertical alignment techniques, with Flexbox the presence of sibling elements doesn’t affect their ability to be vertically aligned.

The HTML


<div class="Aligner">
  <div class="Aligner-item Aligner-item--top">…</div>
  <div class="Aligner-item">…</div>
  <div class="Aligner-item Aligner-item--bottom">…</div>
</div>

The CSS


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

.Aligner-item {
  max-width: 50%;
}

.Aligner-item--top {
  align-self: flex-start;
}

.Aligner-item--bottom {
  align-self: flex-end;
}

And there you have it, vertical centre? No problem now.

It’s good to share

Join the discussion