【问题标题】:Make DIV 100% with overflow-y使用溢出-y 使 DIV 100%
【发布时间】:2013-05-23 19:35:32
【问题描述】:

我有几个 DIV 元素结构,一个放在另一个之下。

<div id="app">
    <div id="title">Title</div>
    <div id="block1">Block 1</div>
    <div id="block2">Block 2</div>
    <div id="content">CONTENT</div>
</div>

#title#block1#block2 具有固定高度,我希望该内容将占用 100% 的可用空间,并且还将具有 overflow-y: auto 即当其内容不适合时会有滚动条。

我该怎么做? 我读过关于使内容绝对定位并将其底部设置为 0px 并将其顶部设置为其他 DIV 高度摘要的想法。但是,我可以在内容块上添加更多 DIV 元素,并且不想一直更改其 CSS。

我也设置了:

html, body, #app {
    height: 100%
}

但是当我将#content 设置为 100% 高度时,它会越过屏幕底部,这不是我需要的。我希望#app 的高度为 100%,#content 刚好适合它,如果需要显示滚动条。

这里是 jsFiddle - http://jsfiddle.net/ZNFcd/

有什么帮助吗?由于它的 Intranet 应用程序因此只适用于 chrome + CSS3 解决方案的解决方案也受到欢迎。

谢谢。

【问题讨论】:

  • 您需要在 html, body 声明中设置 margin:0padding:0 以供初学者使用。您还需要使用box-sizing:border-box;
  • 这个小提琴稍微接近你想要的jsfiddle.net/ZNFcd/1
  • 请查看更新后的答案

标签: html css styles


【解决方案1】:

jQuery 选项

Working Example

var contentHeight = function () {
    var w = $(window).height();
    x = $('#title').height();
    y = $('#block1').height();
    z = $('#block2').height();
    h = w - x - y - z - 3; // -3 to account for borders
    $('#content').height(h);
};

$(document).ready(contentHeight);
$(window).resize(contentHeight);

API documentation for .height()

为此使用一个小脚本具有更灵活的优势。尝试添加或删除内容或更改其他 div 的高度。

纯 CSS 选项

Working Example 2

#app {
    border: 1px solid green;
    height: 100%;
    box-sizing:border-box;
    -moz-box-sizing:border-box
}
#title {
    height: 20px;
}
#block1 {
    height: 30px;
}
#block2 {
    height: 40px;
}
#content {
    height: 90%; /* fallback for browsers without support for calc() */
    height: calc(100% - 90px);
    border: 1px solid red;
    box-sizing:border-box;
    -moz-box-sizing:border-box
}

Documentation for calc()
Documentation for box-sizing

我个人会选择 jQuery 选项,calc() 很酷,但它在 Opera 中不受支持,并且在 Safari 中是“错误的”。

【讨论】:

    【解决方案2】:

    基于@apaul34208的CSS解决方案,可以使用

    html, body {
        padding: 0px;
        margin: 0px;
        height: 100%;
    }
    #app {
        border: 1px solid green;
        height: 100%;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        position: relative;
    }
    #title {
        height: 20px;
    }
    #block1 {
        height: 30px;
    }
    #block2 {
        height: 40px;
    }
    #content {
        position: absolute;
        top: 90px;
        bottom: 0;
        width: 100%;
        border: 1px solid red;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
    }
    

    这样你就不需要calc(),它在旧浏览器上不起作用。

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-08
      • 1970-01-01
      • 2012-02-04
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多