Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexbox "align-items : center" shrinks a child's max-width

Tags:

html

css

flexbox

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>
like image 369
William P. Avatar asked Mar 07 '16 04:03

William P.


2 Answers

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%;
like image 157
Henning Hall Avatar answered Sep 22 '22 13:09

Henning Hall


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

like image 45
vals Avatar answered Sep 21 '22 13:09

vals