我有一个带有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;
答案 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;
...
}
...