CSS中height:100%和height:inherit的異同
by zhangxinxu from http://www.zhangxinxu.com
本文地址:http://www.zhangxinxu.com/wordpress/?p=4642
一、胡聊海聊湊篇幅
上週在微博上無節操吐槽了下inherit
的段子,沒想到回聲還不少:
不過inherit
確實是個好東西,不僅節約代碼,尤其與background
之流打交道;而且還利於維護。
注意,如果想要繼承background
的圖片,不能這樣縮寫,會顯得很天真:
background: #fff inherit left top;
可以這樣子:
background-image: inherit;
二、言歸正傳: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
的差異就可以明顯體現出來了!
您可以狠狠地點擊這裏:height:100%和height:inherit差異demo
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如下:
<div class="outer"><div class="height-100"></div></div> <div class="outer"><div class="height-inherit"></div></div>
結果,height:100%
的衝破雲霄,哦,不對,是深入地域地獄:
而height:inherit
卻完美高度自適應沒有定位特性的父級元素:
對絕對定位有所瞭解的應該都知道原因,我就不解釋了。
總之,這裏,height:inherit
的強大好用可見一斑。回頭,容器高度變化了,裏面的絕對定位元素依然高度自適應。這是很讚的特性,因爲如果頁面很複雜,避免使用position:
relative
會讓你少去很多z-index
混亂層級覆蓋的麻煩。
三、最後說點什麼
本來還想寫一篇Chrome瀏覽器下,表格單元格邊框在opacity
動畫中顯示異常的bug的,結果被媳婦制止了。
嗯哪,寫上癮不一定是好事,休息。本文應該是年前的最後一篇文章了。
本文爲原創文章,會經常更新知識點以及修正一些錯誤,因此轉載請保留原出處,方便溯源,避免陳舊錯誤知識的誤導,同時有更好的閱讀體驗。
本文地址:http://www.zhangxinxu.com/wordpress/?p=4642