2017-07-08 78 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>