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;
}
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.
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%;
}
Add height:80vh;
to .container
and it will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With