首页 > 解决方案 > 应用“align-self:center”时,Flex 孩子会缩小

问题描述

我想水平居中对齐 flex 容器内的 flex 子项。

但是,当孩子得到align-self: center它时,它会缩小到宽度 = 0。

请注意,容器和孩子都有max-width.

你会如何解决这个问题?

.container {
  display: flex;
  flex-direction: column;
  max-width: 400px;
  outline: 2px solid red;
}

.child {
  display: flex;
  flex-direction: column;
  max-width: 200px;
  height: 50px;
  background-color: #ccc;
  /* This causing the child to shrink to width = 0 */
  /* align-self: center; */
}
<div class="container">
  <div class="child">
  </div>
</div>

标签: cssflexbox

解决方案


问题是stretch您通过更改元素的对齐方式禁用的效果。默认情况下align-items设置为stretch因此元素将尝试填充其父宽度(或行方向的高度)。

您可以使用width:100%

.container {
  display: flex;
  flex-direction: column;
  max-width: 400px;
  outline: 2px solid red;
}

.child {
  display: flex;
  flex-direction: column;
  max-width: 200px;
  height: 50px;
  width:100%;
  background-color: #ccc;
  align-self: center; 
}
<div class="container">
  <div class="child">
  </div>
</div>

align-items设置所有弹性容器项目的默认对齐方式,包括匿名弹性项目。align-self 允许为单个弹性项目覆盖此默认对齐方式。参考


推荐阅读