有一个高度自适应的div,里面有两个div,一个高度100px,希望另一个填满剩下的高度。

如果外层div高度自适应于内部,就完全不需要额外写规则了,另外一个DIV绝对能撑高外层div,填得紧紧实实的。

如果是外层div自适应于它的父级,纯CSS的办法是有的。

为了方便演示,下面的demo都让外层元素100%适应于html和body,点Edit in JSFiddle之后可以看到,拖动窗口高度,均能自适应。

box-sizing方案

  1. 外层box-sizing: border-box; 同时设置padding: 100px 0 0
  2. 内层100像素高的元素向上移动100像素,或使用absolute定位防止占据空间;
  3. 另一个元素直接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

  1. 外层position: relative
  2. 百分百自适应元素直接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

posted on 2015-08-13 10:07  pengyingjun  阅读(10219)  评论(0编辑  收藏  举报