【问题标题】:How to position list in the center using flexbox?如何使用 flexbox 将列表定位在中心?
【发布时间】:2019-06-04 13:38:54
【问题描述】:

我有 3 个使用 flexbox 垂直堆叠的盒子。它们现在位于左侧。我想将它们在水平方向居中。我尝试了 div {margin:10px auto} 并且它可以工作,但 css 看起来很尴尬。有没有更优雅的解决方案使用特殊的 flexbox 属性?

我希望 div 居中。

section {
  display: flex;
  flex-direction: column;
  background-color: teal;
}

div {
  background-color: silver;
  width: 200px;
  margin: 10px;
  line-height: 75px;
  font-size: 30px;
}
<section>
	<div>apple</div>
	<div>banana</div>
	<div>pear</div>
</section>

【问题讨论】:

    标签: html css flexbox centering


    【解决方案1】:

    你可以使用align-items: center;

    section {
      display: flex;
      flex-direction: column;
      background-color: teal;
      align-items: center;
    }
    
    div {
      background-color: silver;
      width: 200px;
      margin: 10px;
      line-height: 75px;
      font-size: 30px;
    }
    <section>
    	<div>apple</div>
    	<div>banana</div>
    	<div>pear</div>
    </section>

    【讨论】:

      【解决方案2】:

      您可以使用 align-items: center 将 div 居中,并使用 text-align: center 将 div 内的文本居中,如下所示:

      section {
        display: flex;
        flex-direction: column;
        background-color: teal;
        align-items: center;
        text-align: center;
      }
      
      div {
        background-color: silver;
        width: 200px;
        margin: 10px;
        line-height: 75px;
        font-size: 30px;
      }
      <section>
      	<div>apple</div>
      	<div>banana</div>
      	<div>pear</div>
      </section>

      【讨论】:

      • 优秀。这就是我一直在寻找的。 align-items 效果很好
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 2017-07-25
      • 1970-01-01
      • 2018-01-19
      • 2017-12-17
      • 2016-04-10
      • 2021-03-29
      相关资源
      最近更新 更多