【问题标题】:Vertically center list item content with Flexbox?使用 Flexbox 垂直居中列表项内容?
【发布时间】:2017-12-12 17:59:31
【问题描述】:

我有以下简单的清单...

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 是这样做的吗?

【问题讨论】:

    标签: html css flexbox centering


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以在 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>

      【讨论】:

        猜你喜欢
        • 2016-09-10
        • 2013-03-21
        • 2021-11-06
        • 2013-10-04
        • 2018-06-22
        • 2015-02-28
        • 1970-01-01
        • 1970-01-01
        • 2017-12-13
        相关资源
        最近更新 更多