有一個高度自適應的div,里面有兩個div,一個高度100px,希望另一個填滿剩下的高度。
如果外層div高度自適應於內部,就完全不需要額外寫規則了,另外一個DIV絕對能撐高外層div,填得緊緊實實的。
如果是外層div自適應於它的父級,純CSS的辦法是有的。
為了方便演示,下面的demo都讓外層元素100%適應於html和body,點Edit in JSFiddle之后可以看到,拖動窗口高度,均能自適應。
box-sizing方案
- 外層
box-sizing: border-box;
同時設置padding: 100px 0 0
; - 內層100像素高的元素向上移動100像素,或使用absolute定位防止占據空間;
- 另一個元素直接
height: 100%;
這就是兩個方案了
第一種方案:
html代碼:
<div class="outer"> <div class="A"></div> <div class="B"></div> </div>
css代碼:
html, body { height: 100%; padding: 0; margin: 0; } .outer { height: 100%; padding: 100px 0 0; box-sizing: border-box ; } .A { height: 100px; margin: -100px 0 0; background: #BBE8F2; } .B { height: 100%; background: #D9C666; }
第二種方案:
html代碼:
<div class="outer"> <div class="A"></div> <div class="B"></div> </div>
css代碼:
html, body { height: 100%; padding: 0; margin: 0; } .outer { height: 100%; padding: 100px 0 0; box-sizing: border-box ; position: relative; } .A { height: 100px; background: #BBE8F2; position: absolute; top: 0 ; left: 0 ; width: 100%; } .B { height: 100%; background: #D9C666; }
absolute positioning
- 外層
position: relative
; - 百分百自適應元素直接
position: absolute; top: 100px; bottom: 0; left: 0
第三個方案:
html代碼:
<div class="outer"> <div class="A"></div> <div class="B"></div> </div>
css代碼:
html,
body { height: 100%; padding: 0; margin: 0; }
.outer { height: 100%; position: relative; }
.A { height: 100px; background: #BBE8F2; }
.B { background: #D9C666; width: 100%; position: absolute; top: 100px ; left: 0 ; bottom: 0; }
注意一下,這三個方案都是IE8+。
文章來源:http://segmentfault.com/q/1010000000762512/a-1020000000762933