cssflexboxshrink

How can we shrink middle flex item?


I am trying to make a layout from flexbox. I have 3 column of boxes which have following layout till they reach mobile layout where they will stack on top of another. But before I reach mobile layout I am trying to shrink all the items proportionally. (i.e when I reduce the browsers width, it should equally be small). But only the left and right items are equally reducing except the middle item. How do I make that shrink so that all the items proportionally shrink while reducing browsers width?

CODE GOES HERE

.container {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 80px;
}

.box {
  width: 400px;
  /*   min-width: 280px; */
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid black;
  font-size: 30px;
  font-weight: bold;
  font-family: cursive;
  box-shadow: 1px 4px 3px rgba(0, 0, 0, 0.5);
}
.box1 {
  background: grey;
}
.box2 {
  background: green;
  margin-bottom: 20px;
}
.box3 {
  background: greenyellow;
}
.box4 {
  background: orange;
}
.middle-part {
  margin: 0px 20px;
  /*   min-width: 280px; */
}
<div class="container">
  <div class="box box1">
    I am box1
  </div>
  <div class="middle-part">
    <div class="box box2">
      I am box2
    </div>
    <div class="box box3">
      I am box3
    </div>
  </div>
  <div class="box box4">
    I am box4
  </div>
</div>


Solution

  • If you want it to shrink dynamically, you need to remove the width set. Add flex-grow: 1 on .box and .middle-part to make it grow. In addition, padding-top only accept 1 value, so perhaps some typos there.

    .container {
      width: 100%;
      height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      padding-top: 80px 40px; /* padding top only accept 1 value */
    }
    .middle-part {
      flex-grow: 1;
    }
    .box {
      flex-grow: 1;
      /*   min-width: 280px; */
      height: 400px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid black;
      font-size: 30px;
      font-weight: bold;
      font-family: cursive;
      box-shadow: 1px 4px 3px rgba(0, 0, 0, 0.5);
    }
    .box1 {
      background: grey;
    }
    .box2 {
      background: green;
      margin-bottom: 20px;
    }
    .box3 {
      background: greenyellow;
    }
    .box4 {
      background: orange;
    }
    .middle-part {
      margin: 0px 20px;
      /*   min-width: 280px; */
    }
    <body>
      <div class="container">
        <div class="box box1">
          I am box1
        </div>
        <div class="middle-part">
          <div class="box box2">
            I am box2
          </div>
          <div class="box box3">
            I am box3
          </div>
        </div>
        <div class="box box4">
          I am box4
        </div>
      </div>
    </body>