Vertically Centering with Flexbox

Publikováno: 8.5.2018

Vertically centering sibling child contents is a task we’ve long needed on the web but has always seemed way more difficult than it should be.  We initially used tables to accomplish the task, then moved on to CSS and JavaScript tricks because table layout was horribly inefficient — yet it seemed that tables were the […]

The post Vertically Centering with Flexbox appeared first on David Walsh Blog.

Celý článek

Vertically centering sibling child contents is a task we’ve long needed on the web but has always seemed way more difficult than it should be.  We initially used tables to accomplish the task, then moved on to CSS and JavaScript tricks because table layout was horribly inefficient — yet it seemed that tables were the easiest and most reliable way to make vertical centering happen.  When the vertical-align CSS property was introduced, I was incredibly excited, but quickly found that it didn’t usually do what I wanted it to.

After playing with flexbox for the DevTools Debugger I’ve found that align-items: center; is the hero I’ve always needed.

Let’s consider the following HTML markup which features contents of varying heights:

<div class="demo-content-parent">
  <div>Hello!</div>
  <div><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra.</p></div>
  <div><img src="https://davidwalsh.name/wp-content/themes/punky/images/logo.png" style="display: inline;"></div>
</div>

If we want each elements’ contents to be vertically centered, we can use flexbox and align-items to make that happen:

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

Flexbox was always promised to be the savior of web layout but appears to have flamed out a bit in favor of CSS grid; I’m just happy that flexbox fixed the vertical alignment issue that caused us all nightmares for so long!

The post Vertically Centering with Flexbox appeared first on David Walsh Blog.

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace