vincentsty vincentsty - 6 months ago 18
HTML Question

Calculate dynamic height via css

I have something as below. Theoretically, an image above and a div below. The image and the div fits into a full page, in which the div takes the remaining of the image height, in which when the content overflows the height, it can be scrollable.

Keyword: Image with dynamic height, pure css solution

And my question is: Is this possible to be done purely by css alone?

I am expecting something like this

<div id="outer">
<img id="image" src="" style="width: 100%;">
<div id="inner" style="height:calc(100% - imageHeight);"></div>
</div>


enter image description here

Answer

You can use flex:

html, body, #outer {
  height:100%;
  margin:0;
  box-sizing:border-box;/* includes padding and border to size calculation */
  }
#outer {
  display:flex; 
  flex-direction:column;
  }
#image {
  width:100%;
  }
#inner {
  flex:1;/* will use whole space left below image if height is set an #outer */
  background:tomato;
  overflow:auto; 
  }
<div id="outer">
    <img id="image" src="http://dummyimage.com/400x50&text=Header_image" />
    <div id="inner" >inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/>inner <br/></div>
</div>

example with flex properties https://jsfiddle.net/0j6xzdds/2/