2017-07-08 34 views
3

我有以下的简单列表...使用Flexbox垂直居中显示项目内容?

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的做到这一点的呢?

回答

4

是flexbox对此很好。您可以使用现有布局,只需在li上使用inline-flex,然后将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>

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>