6

I'm trying to make a stacked layout using flexbox. Ideally it'd look like this:

2 boxes stacked vertically, the top is red and 4x the size of the bottom, which is blue

where the bottom (blue) div is a fixed height of 250px and the top div is n-250, where n is the size of the parent container--in another words, the top should stretch to fill the container.

I have some idea of how to do this when I have the container height, but I'd rather avoid having to determine that variable at runtime.

This issue has been covered at length in various forms , but none seem to address this simple use-case (here, for example, works with a header/content/footer, but ostensibly not with just content/footer).

I've set up a codepen with the example.

Community
  • 1
  • 1
Brandon
  • 7,736
  • 9
  • 47
  • 72
  • 1
    Why is this anything more complicated than a `flex-grow` on the top div? –  Jan 05 '17 at 05:14
  • 1
    FYI in your codepen you have 2 errors in the HTML that prevent it working. instead of and bottom="bottom" instead of id="bottom" – Brad Jan 05 '17 at 05:14
  • 1
    http://codepen.io/anon/pen/ygygmy – Brad Jan 05 '17 at 05:17
  • 1
    If the height of the container isn't known or resolveable (e,g, a fixed value) then, in general, *you can't*. Note all of the current answers below require that the height of the container is known. If it isn't...they won't work AFAIK. – Paulie_D Jan 05 '17 at 12:57

3 Answers3

11

I think this is answering your question using the flex-grow: 1;. hope it helps

https://jsfiddle.net/BradChelly/ck72re3a/

.container {
  width: 100px;
  height: 150px;
  background: #444;
  display: flex;
  flex-direction: column;
  align-content: stretch;
}
.box1 {
  width: 100%;
  background: steelblue;
  flex-grow: 1;
}
.box2 {
  height: 50px;
  width: 100%;
  background: indianred;
}
<div class="container">
  <div class="box1"></div>
  <div class="box2"></div>
</div>
Brad
  • 8,044
  • 10
  • 39
  • 50
3

Minimum line of code. Brad's answer is correct. But here I used flex instead of flex-grow and removed align-items

.container {
  width: 100px;
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.top {
  width: 100%;
  background: blue;
  flex: 1;
}
.bottom {
  height: 70px;
  width: 100%;
  background: green;
}
<div class="container">
  <div class="top"></div>
  <div class="bottom"></div>
</div>

Demo here

Syam Pillai
  • 4,967
  • 2
  • 26
  • 42
1

That can be done without flexbox by simply using CSS Calc

html, body {
  margin: 0;
}
.container {
  height: 100vh;
}
.top {
  background: lightblue;
  height: calc(100% - 100px);
}
.bottom {
  height: 100px;
  background: lightgreen;
}
<div class="container">
  <div class="top"></div>
  <div class="bottom"></div>
</div>

If you want it to work on older browsers, update these rules like this

html, body {
  margin: 0;
  height: 100%;
}
.container {
  height: 100%;
}
Asons
  • 84,923
  • 12
  • 110
  • 165