Flexbox" align-items:center"缩小孩子的最大宽度

时间:2016-03-07 04:54:27

标签: html css css3 flexbox

我有一个带有container的flexbox div align-items: center,有三个孩子。其中一个有max-width: 200px(代码中为second-ch),它也是一个带有justify-content: space-between分发的两个孩子的flex,但是second-ch没有关注它的max-width。如果我从align-items: center移除container,则second-ch会再次获取所需的宽度,但其余元素不再位于中心。我该如何解决?



.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}

.first-ch {
  width: 70px;
  height: 70px;
  background-color: grey;
}

.second-ch {
  max-width: 200px;
  height: 80px;
  background-color: red;
  display: flex;
  justify-content: space-between;
}
  .square {
    width: 50px;
    height: 50px;
    background-color: yellow;
    margin: 5px;
  }
.third-ch {
  width: 50px;
  height: 50px;
  background-color: blue;
}

<div class="container">
  <div class="first-ch"></div>
  <div class="second-ch">
    <div class="square"></div>
    <div class="square"></div>
  </div>
  <div class="third-ch"></div>
</div>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:1)

为什么使用max-width: 200px;?试试width: 200px; 当您使用align-items : center时,.second-ch具有所需的最小宽度。 max-width限制块的最大宽度,但不设置最小宽度

答案 1 :(得分:1)

引用Jason Deppen的评论:

我还通过设置width:100%以及我的最大宽度值来解决了这个问题。

max-width: <you max width>;
width: 100%;

答案 2 :(得分:0)

为什么会这样?

这并不是对齐项目的影响:中心。这是默认值的缺省,align-items:stretch,这会让孩子成长。

.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: stretch;   /* default */
}

.first-ch {
  width: 70px;
  height: 70px;
  background-color: grey;
}

.second-ch {
  max-width: 200px;
  height: 80px;
  background-color: red;
  display: flex;
  justify-content: space-between;
}
  .square {
    width: 50px;
    height: 50px;
    background-color: yellow;
    margin: 5px;
  }
.third-ch {
  width: 50px;
  height: 50px;
  background-color: blue;
}
<div class="container">
  <div class="first-ch"></div>
  <div class="second-ch">
    <div class="square"></div>
    <div class="square"></div>
  </div>
  <div class="third-ch"></div>
</div>

如果您希望孩子长大直到达到width-max,请按照bolverin说明并明确设置宽度

答案 3 :(得分:0)

我知道这很旧,但对于任何阅读此内容的人来说:

在子元素上使用 align-self: stretch; 也可以:)

所以在这种情况下:

.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}

...

.second-ch {
  max-width: 200px;
  align-self: stretch;
  ...
}

...