Reputation: 1
Basically, I gave the parent container a min-height of 50%, and the child container a height of 50%. I put lots of text inside the parent container, so it will expand say to 60%. I tried the height: 1px trick. It did not work. Basically the child container remains at 50% of parent's min-height (i.e. 50%) instead of 50% of the parent's actual height (e.g. 60%).
html,
body {
height: 100%;
}
#parent {
width: 50%;
height: 1px;
min-height: 50%;
background-color: yellow;
}
#child {
background-color: red;
height: 50%;
}
<div id="parent">
dsds dsfdsf sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf
sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf sdffds sddfsdsds dsfdsf sdffds
<div id="child">
Hello World!
</div>
</div>
Edit:
An application of this is to create a full page div that is allowed to grow when there is an overflow (i.e. min-height 100%). This full page div can contain a child container (e.g. a non-absolute or fixed header) with percentage height as described in the scenario above.
Upvotes: 0
Views: 911
Reputation: 17350
You cannot do this for a simply reason: your #child
is actually expanding your parent - it is part of the content. You might notice that if you give your parent a relative
height, and the child an absolute
height, the 50%
does work. But that is because your content has been taken out of regular flow.
The simply logical reason you can use to justify this behaviour is to try and solve it mathematically. Let's say we have p
, which is the parents height, and e
which is the height of the content other than the child. That makes c
the child height, or h / 2
. The equation to calculate the Child height would therefor be:
var c = (e + c) / 2
Which you cannot solve, as it turns into this:
var c = (e + (e + (e + (e + ... ) / 2) / 2) / 2) / 2
Which, if the ...
doesn't tell you, is unsolvable.
This problem cannot be alleviated without breaking from the regular flow and making your size relative to something that can be calculated.
Upvotes: 1