如何拉伸div高度来填充父div - CSS

时间:2011-04-07 13:23:59

标签: css css3

我有一个包含div的页面,如下所示

<div id="container">
    <div id="A">
    </div>
    <div id="B">
        <div id="B1"></div>
        <div id="B2">B2</div>
    </div>
    <div id="C"></div>
    <div id="D">
    </div>
</div>

造型为;

html, body {
    margin: 0;
    padding: 0;
    border: 0;
}
#B, #C, #D {
    position: absolute;
}
#A{
    top: 0;
    width: 100%;
    height: 35px;
    background-color: #99CC00;
}
#B {
    top: 35px;
    width: 200px;
    bottom: 35px;
    background-color: #999999;
    z-index:100;
}
#B2 {
    margin-top: -35px;
    bottom: 0;
    background-color: #FFFFFF;
    width: 200px;
    overflow: scroll;
}
#B1 {
    height: 35px;
    width: 35px;
    margin-left: 200px;
    background-color: #CC0066;
}
#C {
    top: 35px;
    left: 200px;
    right: 0;
    bottom: 35px;
    background-color: #CCCCCC;
}
#D {
    bottom: 0;
    width: 100%;
    height: 35px;
    background-color: #3399FF;
}

我想调整div B2的高度以填充(或延伸到)整个div B(标有绿色边框)并且不想跨越页脚div D.这是工作小提琴demo(已更新)。我怎么解决这个问题?

6 个答案:

答案 0 :(得分:33)

只需将height: 100%;添加到#B2样式上即可。 <{1}}不应该是必要的。

答案 1 :(得分:12)

假设你有

<body>
  <div id="root" />
</body>

使用普通的CSS,您可以执行以下操作。查看有用的应用https://github.com/onmyway133/Lyrics/blob/master/index.html

#root {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

使用flexbox,您可以

html, body {
  height: 100%
}
body {
  display: flex;
  align-items: stretch;
}

#root {
  width: 100%
}

答案 2 :(得分:9)

http://jsfiddle.net/QWDxr/1/

使用“min-height”属性
警惕填充,边距和边界:)

html, body {
    margin: 0;
    padding: 0;
    border: 0;
}
#B, #C, #D {
    position: absolute;
}
#A{
    top: 0;
    width: 100%;
    height: 35px;
    background-color: #99CC00;
}
#B {
    top: 35px;
    width: 200px;
    bottom: 35px;
    background-color: #999999;
    z-index:100;
}
#B2 {
    min-height:100%;
    height:100%
    margin-top: -35px;
    bottom: 0;
    background-color: red;
    width: 200px;
    overflow: scroll;
}
#B1 {
    height: 35px;
    width: 35px;
    margin-left: 200px;
    background-color: #CC0066;
}
#C {
    top: 35px;
    left: 200px;
    right: 0;
    bottom: 35px;
    background-color: #CCCCCC;
}
#D {
    bottom: 0;
    width: 100%;
    height: 35px;
    background-color: #3399FF;
}

答案 3 :(得分:5)

如果您要使用B2进行造型,可以试试这个“黑客”

#B { overflow: hidden;}
#B2 {padding-bottom: 9999px; margin-bottom: -9999px}

jsFiddle

答案 4 :(得分:4)

我的目的是创建一个总是在整个浏览器窗口中固定数量的div。

至少在firefox上有用的是这个

<div style="position: absolute; top: 127px; left: 75px;right: 75px; bottom: 50px;">

如果实际窗口没有强制滚动,div在所有重新调整大小的过程中都会将其边界保留到窗口边缘。

希望这能节省一些时间。

答案 5 :(得分:-5)

如果尺寸可以变化,我会用javascript解决方案(jquery)来解决它。

window.setTimeout(function () {
    $(document).ready(function () {
        var ResizeTarget = $('#B');

        ResizeTarget.resize(function () {
            var target = $('#B2');
            target.css('height', ResizeTarget.height());
        }).trigger('resize');
    }); 
}, 500);
相关问题