1. 原因
  2. 解决办法
  3. 参考

height百分比值不生效

有时候要给父元素定一个最小高度,然后让子元素与父元素等高.
往往第一反应是设置min-height和height: 100%,但这么作通常不会生效.

1.PNG
如上图所示,外层容器的高度为min-height: 100px,内部黄色子元素的高度为height: 50%.
可以观察到,子元素的height: 50%并未生效.

对应代码:

1
2
3
<div class="wrapper">
<div class="child">1</div>
</div>
1
2
3
4
5
6
7
8
9
10
.wrapper {
width: 100px;
min-height: 100px;
border:1px solid;
}

.child {
height: 50%;
background: yellow;
}

原因

先看一下CSS2.1对height百分比值计算的描述:

1
2
3
4
The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.

百分比值相对于父元素的高度计算.
如果没有"明确定义"父元素的高度,并且该元素没有被"绝对定位",则最终的计算结果为auto.

关键就在于规范中的"specified explicitly".
min/max-height的作用是把元素高度限制在一个范围之内,而非一个具体的值.
所以,height: 50%没有生效,最终的计算结果是height: auto.

解决办法

1 如果要让子元素和父元素等高,则可以给子元素添加min-height: inherit属性.
注意:是min-height,而非height.
2.PNG

2 如果子元素和父元素不等高(例如50%),则可以给父元素添加height: 1px来解决. 
3.PNG

这是个糟糕的方法,height: 1px实际上把高度给锁死了.
当子元素超过min-height时,父元素并不会自动变高.
既然不能变高,那就没必要给父元素设置min-height了.
4.PNG

3 利用表的特点,为父元素和子元素分别添加display:table和table-cell属性.
说到table,最常想到的就是display:table + display:table-cell + vertical-align: middle 居中多行文字.
这里只用了前两个属性, 让子元素自动撑开与父元素等高.
5.PNG

参考

css - min-height和height的疑问? - SegmentFault 思否
css - Child inside parent with min-height: 100% not inheriting height - Stack Overflow
height与min-height的百分比问题和铺满屏幕的布局方法 - 进击的面包君 - 博客园