应用“ align-self:center”时,柔体子收缩

时间:2019-01-30 23:37:55

标签: css flexbox

我想在flex容器内水平居中对齐flex子级。

但是,当孩子得到align-self: center时,它会缩小到width = 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>

1 个答案:

答案 0 :(得分:3)

问题是您通过更改元素的对齐方式禁用的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为所有flex容器的项目(包括匿名flex项目)设置默认对齐方式。 align-self 允许单个弹性项目覆盖此默认对齐方式 ref