I have a flexbox div container
with align-items: center
, with three childs. One of them has max-width: 200px
(in the code, second-ch
), and it's also a flex with two childs distributed with justify-content: space-between
, but second-ch
is not following its max-width
. If I remove align-items: center
from container
, second-ch
takes again the width desired but the remaining elements are not in the center anymore. How can I solve that?
.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>
Citing the comment of Jason Deppen:
I solved it by also setting width: 100% along with my max-width value.
max-width: <your max width>;
width: 100%;
Why is this happening ?
It's not really the effect of align-items: center. It's the omision of the default value, align-items: stretch , that makes the child grow.
.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>
If you want the child to grow until it reaches the width-max, do as bolverin says and set the width explicitly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With