说明:原文链接 http://www.zhangxinxu.com/wordpress/2015/02/different-height-100-height-inherit/comment-page-1/
原文总览:
height:100%和height:inherit的异同
1. 兼容性差异
height:100%
IE6+ √
height:inherit
IE8+ √
2. 大多数情况作用是一样的
除去兼容性,大多数情况下,两者作用是一样的,甚至都很难想出不一样的理由。
① 父容器height: auto
,无论height:100%
或者height:inherit
表现都是auto
.
② 父容器定高height: 100px
,无论height:100%
或者height:inherit
表现都是100px
高.
难道没有差异吗?难道没有使用height:inherit
的理由吗?当然有,记住,江湖上所发生的一切事情,都绝非偶然!
3. 绝对定位大不同
当子元素为绝对定位元素,同时,父容器的position
值为static
的时候,呵呵呵,height:100%
和height:inherit
的差异就可以明显体现出来了!
CSS代码:
<pre name="code" class="css">.outer {
display: inline-block;
height: 200px; width: 40%;
border: 5px solid #cd0000;
}
.height-100 {
position: absolute;
height: 100%; width: 200px;
background-color: #beceeb;
}
.height-inherit {
position: absolute;
height: inherit; width: 200px;
background-color: #beceeb;
}
HTML代码:
<pre name="code" class="DlHighlight html" style="font-stretch: normal; font-size: 14px; line-height: 1.3; font-family: Consolas, Monaco, monospace; padding: 5px 10px; margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; word-wrap: break-word; color: rgb(51, 51, 51); background-color: rgb(255, 255, 255);"><pre name="code" class="DlHighlight html" style="margin-top: 0px; margin-bottom: 0px; color: rgb(51, 51, 51); font-size: 14px; line-height: 1.3; font-stretch: normal; font-family: Consolas, Monaco, monospace; padding: 5px 10px; white-space: pre-wrap; word-wrap: break-word; background-color: rgb(255, 255, 255);"><span class="paren xml-tagangle" style="color: rgb(0, 0, 153);"></span><pre name="code" class="html"><div class="outer"><div class="height-100"></div></div>
<div class="outer"><div class="height-inherit"></div></div>
结果:
<img src="https://img-blog.csdn.net/20160818180124141?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
4. 总结
总之,这里,height:inherit
的强大好用可见一斑。回头,容器高度变化了,里面的绝对定位元素依然高度自适应。这是很赞的特性,因为如果页面很复杂,避免使用position: relative
会让你少去很多z-index
混乱层级覆盖的麻烦。
大神的网站: http://www.zhangxinxu.com/wordpress/