2

I want to make a typical Header/Content/Footer Layout in CSS with Flexbox. Header and Footer should have a fixed size. The Content should scale with the wrapper, so I thought I give it a flex property of 1.

Works pretty well, but I want to have a img in the Content div that scales up to 100% in height of the div.

For small Images it works but when it exceets the size of the content div, the div scales to the img??

I modeled the Problem:

.wrapper{
  display: flex;
  flex-direction: column;
  height:200pt;
  background: grey;
}

.a{
  height:50pt;
  background: blue;
}

.b{
  flex: 1;
  background: red;
}

.b img{
    height:100%;
}

.c{
  height:50pt;
  background: green;
}
<div class="wrapper">
  <div class="a"></div>
  <div class="b">
    <!--

With Small Image it works!

<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/85/WLE_Austria_Logo_%28no_text%29.svg/50px-WLE_Austria_Logo_%28no_text%29.svg.png">
-->
    
    <img src="https://i.chzbgr.com/full/7006036736/h52434C0A/computer-says-no">
    
  </div>
  <div class="c"></div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415

2 Answers2

7

The reason why this happens with flex is that the flex container by default cannot be smaller than its content. So even if you set its height to 100%, the moment you put more content in it than fits, it will expand.

The solution for that is using min-height: 0 on this flex container.

.wrapper {
  display: flex;
  flex-direction: column;
  height: 200pt;
  background: grey;
}

.a {
  height: 50pt;
  background: blue;
}

.b {
  flex: 1;
  background: red;
  min-height: 0;
}

.b img {
  height: 100%;
}

.c {
  height: 50pt;
  background: green;
}
<div class="wrapper">
  <div class="a"></div>
  <div class="b">
    <img src="https://i.chzbgr.com/full/7006036736/h52434C0A/computer-says-no">
  </div>
  <div class="c"></div>
</div>
The Fool
  • 16,715
  • 5
  • 52
  • 86
  • 1
    Wow, that was unintuitive, but you are totally right, works like a charm :) Thank you very much – Gianluca Corazza May 04 '20 at 10:51
  • Ok... min-height somehow fixed my grow-issues. Going to read this 10 more times later to try understanding WHY. So far, thank you very much! – C4d Nov 15 '22 at 10:34
0

I think the best solution would be to not use the fixed height for the wrapper to allow the wrapper to scale based on its content. Also, give image display block to get rid of unnecessary spacing:

.b img{
  display: block;
}

.wrapper{
  min-height:200pt;
}
Leon Vuković
  • 489
  • 3
  • 16