使用Flexbox垂直居中列表项内容?

时间:2017-07-08 15:18:16

标签: html css css3 flexbox centering

我有以下简单列表......

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;display:inline-block;margin-right:10px;background:green;color:white;}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

我正在尝试将项目内容垂直居中,是否可以使用flexbox进行此操作?

2 个答案:

答案 0 :(得分:5)

是的,flexbox非常适合这一点。您可以使用现有布局,只需使用inline-flex上的li并设置align-items: center即可将内容垂直居中。

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;display:inline-flex;margin-right:10px;background:green;color:white;align-items:center;}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

您也可以将内容的line-height设置为父级的高度,并将内容垂直居中。

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;display:inline-block;margin-right:10px;background:green;color:white;line-height:200px;}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

答案 1 :(得分:0)

您可以在李的顶部添加填充

ul{background:wheat;height:200px;text-align:center;}
li{height:200px;padding-top: 100px;display:inline-block;margin-right:10px;background:green;color:white;}
since you directly defined the height of the box I was able to just divide that value in half in order to center the content using padding. If you don't know the difference between padding margin and border. Look into the box model in css. It is one of the most fundamental concepts you will need to grasp to have a good understanding of css.

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>