Wil*_* P. 9 html css css3 flexbox
我有一个Flexbox的DIV container用align-items: center,有三个孩子的.其中一个max-width: 200px(在代码中second-ch),它也是一个flex,有两个子分发justify-content: space-between,但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>Hen*_*all 11
引用 Jason Deppen 的评论:
我还通过设置 width: 100% 和我的 max-width 值来解决它。
max-width: <your max width>;
width: 100%;
我知道这已经很旧了,但对于读过这篇文章的人来说:
在子元素上使用align-self: stretch;也可以:)
所以在这种情况下:
.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}
...
.second-ch {
  max-width: 200px;
  align-self: stretch;
  ...
}
...
为什么会出现这种情况?
这并不是真正的align-items: center 的效果。正是省略了默认值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>如果您希望子级增长直到达到最大宽度,请按照 bolverin 的说明进行操作并显式设置宽度
你为什么用max-width: 200px;?width: 200px;
当您使用所需的align-items : center最小宽度时尝试.second-ch。
max-width限制块的最大宽度,但不设置最小宽度
| 归档时间: | 
 | 
| 查看次数: | 2783 次 | 
| 最近记录: |