首页 > 解决方案 > 如何使用 flexbox 将列表定位在中心?

问题描述

我有 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>

标签: htmlcssflexboxcentering

解决方案


你可以使用 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>


推荐阅读