使用弹性框垂直居中列表项内容?



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

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 是执行此操作的方法吗?

是的,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>

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

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>

最新更新