Bootstrap 4 - Vertically Centering List Items

2019-06-21 18:26发布

问题:

I have a web page that uses the Bootstrap 4 beta. In this page, I have an inline list. I want the content of each list item to be vertically centered so the items line up. As shown in this Bootply, they're currently off-center. I'm using the following code:

<ul class="list-inline text-center align-items-center">
  <li class="list-inline-item"><h2>Hello</h2></li>
  <li class="list-inline-item"><button class="btn btn-info btn-sm">Help</button></li>
</ul>

My question is, how do I get the list items to be vertically centered?

回答1:

It looks as though flexbox hasn't been applied

Try this:

.align-items-center {
    -ms-flex-align: center!important;
    align-items: center!important;
    display: flex;
    justify-content: center;
}

Bootply Demo

Note: there is no CSS method of vertically aligning the contents of elements that do not share a parent with each other. The above aligns the li...not their contents..but seems to have the effect you are looking for.



回答2:

Use the included flexbox utils (no extra CSS is needed)..

<ul class="list-inline text-center d-flex justify-content-center align-items-center">
  <li class="list-inline-item"><h2>Hello</h2></li>
  <li class="list-inline-item"><button class="btn btn-info btn-sm">Help</button></li>
</ul>

https://www.bootply.com/NLcGDLFEjJ



回答3:

Its very simple. Just add the bootstrap class align-middle to both the <li> tags.

<ul class="list-inline text-center align-items-center">
  <li class="list-inline-item align-middle"><h2>Hello</h2></li>
  <li class="list-inline-item align-middle"><button class="btn btn-info btn-sm">Help</button></li>
</ul>

Hope this helps. You can check the result here.