lonecatly
lonecatly

Reputation: 303

flex-grow not expanding flex item

First I create a layout using flexbox:

<html>
  <body>
    <div id="header"></div>
    <div id="main"></div>
  </body>
</html>

header div has a fixed height: 60px, and main div takes the remaining height of screen:

html, body{
  100%;
}
body{
  display: flex;
  flex-direction: column;   
}
#header{
  height: 60px;
  flex-grow: 0;
}
#main{
  flex-grow: 1;
}

I got what I want:

header and main div

Then I want to display three boxes inside #main div: box_1, box_2 and box_3. box_1 and box_3 has the same height value, and box_2 expand itself to take the remaining height of #main:

What I want:

I add the following codes:

<html>
  <body>
    <div id="header"></div>
    <div id="main">
      <div id="box_1"></div>
      <div id="box_2"></div>
      <div id="box_3"></div>
    </div>
  </body>
</html>

#main{
  flex-grow: 1;
  flex-direction: column;
}
#box_1, #box_3{
    height: 60px;
    flex-grow: 0;
    background-color: red;
}
#box_2{
    flex-grow: 1;
    background-color: blue;
}

The #box_2 is invisible unless I set a height value to #main div. If height value is required, why should I still use flexbox...

Upvotes: 6

Views: 11948

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 372264

The main problem in your code is that you didn't specify display: flex on the #main container.

Therefore, the element is not a flex container, flex-direction: column is ignored, and the children are not flex items.

Keep in mind that flex properties work only between parent and child elements. So your display: flex on the body element applies only to the children, but not other descendants.

body {
  display: flex;
  flex-direction: column;
  height: 100vh;
  margin: 0;
}

header {
  flex: 0 0 60px;               /* flex-grow, flex-shrink, flex-basis */
  background-color: lightgray;
}

main {
  flex-grow: 1;
  background-color: aqua;
  display: flex;                 /* key addition */
  flex-direction: column;
}

#box_1, #box_3 {
  flex: 0 0 60px;
  background-color: red;
}

#box_2 {
  flex-grow: 1;
  background-color: blue;
}
<header></header>
<main>
  <div id="box_1"></div>
  <div id="box_2"></div>
  <div id="box_3"></div>
</main>

Upvotes: 8

Related Questions