Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a flex element fully expand to fill the containing element?

Tags:

html

css

flexbox

Here is my code.

I want the element .container to fully expand and occupy the area of .toplevel.

.toplevel {
  height: 100%;
  min-height: 800px;
  border: solid 1px blue;
}

.container {
  display: flex;
  border: solid 1px red;
  height: 100%;
  flex: 0 1 auto;
  flex-direction: column;
  // min-height: 800px;
}

.up {
  display: flex;
  flex: 1 1 auto;
}

.down {
  display: flex;
  flex: 0 1 auto;
}
<div class="toplevel">
  <div class="container">
    <div class="up">
      This is up
    </div>
    <div class="up">
      This is down
    </div>
  </div>
</div>

However it seems like the only way to make the .container larger height-wise is to define a min-height. It is too inflexible because I will have provide a different value for different device form factor.

How can I fix it?

like image 742
Anthony Kong Avatar asked Dec 18 '22 02:12

Anthony Kong


1 Answers

Simpy add display: flex to .toplevel and remove height: 100% from .container.

This work based on the fact that flex row item's height behavior can be controlled with the align-items property. As it by default has stretch, it will fill its parents height.

As a note, in general, when it comes to Flexbox, it is preferable to make use of its own properties instead of height/width. By doing so you also get a better cross browser support.

Stack snippet

.toplevel {
  height: 100%;
  min-height: 800px;
  border: solid 1px blue;
  display: flex;              /* added  */
}

.container {
  display: flex;
  border: solid 1px red;
  /*height: 100%;                removed  */
  flex: 1 1 auto;            /*  changed, flex row item need the grow value
                                          to be 1 to fill its parent's width  */
  flex-direction: column;
}

.up {
  display: flex;
  flex: 1 1 auto;
}

.down {
  display: flex;
  flex: 0 1 auto;
}
<div class="toplevel">
  <div class="container">
    <div class="up">
      This is up
    </div>
    <div class="down">
      This is down
    </div>
  </div>
</div>
like image 95
Asons Avatar answered Dec 26 '22 19:12

Asons