WordPress / Web Development Tutorials
(Best WordPress Tutorials)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
Silva Web Designs - Blog

How to Align Items in a Flex Container – 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.

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital-related. His main expertise is with WordPress and various other CMS frameworks. If you need responsive design, SEO, speed optimisation or anything else in the world of digital, you can contact Silva Web Designs here; [email protected]

It’s good to share

Join the discussion