如何使用弹性框将列表定位在中心



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

我想在中心有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>

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

您可以使用

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>

最新更新