Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

height: 100% not working when parent div only has max-height

Can't wrap my head around it! I try to make parent div to take no more than 80% height of the window with max-height, and child div to take all parent height minus something.

But height property in percents of the parent doesn't work for the child at all, unless I give parent height property.

Why is that?

Here is my simplified fiddle: https://jsfiddle.net/mbatcer/m2ohnsf5/ Why does inner div not respect parent height and go out of container?

HTML:

<div class="container">
  <div class="inner">
    <img src="http://via.placeholder.com/70x300">
  </div>
</div>

CSS:

.container {  
  background: blue; 
  padding: 10px; 
  max-height: 100px; 
}

.inner { 
  height: 100%;
  width: 70px;
  overflow: hidden;
}
like image 289
Mikhail Batcer Avatar asked Aug 07 '17 17:08

Mikhail Batcer


Video Answer


3 Answers

I think this is what you are looking for:

.container {  
  background: blue; 
  padding: 10px; 
  max-height: 100px; 
  display: flex;

}

.inner { 
  width: 70px;
  overflow: hidden;
}

Here is the fiddle: https://jsfiddle.net/f9sfczya/1/

Here I added display: flex; in your parent div and removed height: 100%; from child div.

Unfortunately display: flex; is unsupported by IE9 and older.

Hope this may help you.

like image 153
Achyutam Avatar answered Nov 10 '22 13:11

Achyutam


If you set child's max-height with a percentage, it will set the child's height according to the parent's real height instead of the max-height. So you will need to set a height to your .container and set a max-height: 100% to your image since your image has lager height than width.

.container {  
  background: blue; 
  padding: 10px; 
  height: 100px; 
}

.inner { 
  height: 100%;
  overflow: hidden;
}

img {
  max-height: 100%;
}

A better way to solve this problem is to use flex-box.

.container {
  display: flex;
  flex-flow: row;  
  background: blue; 
  padding: 10px; 
  max-height: 80vh; 
}

.inner { 
  overflow: hidden;
}

img {
  max-height: 100%;
}
like image 25
brian17han Avatar answered Nov 10 '22 15:11

brian17han


Add height:80vh; to .container and it will work.

like image 36
Our_Benefactors Avatar answered Nov 10 '22 15:11

Our_Benefactors