基于百分比的 Div 高度但仍可滚动

6

首先,类似但从未得到答案的问题:

垂直滚动百分比高度、垂直边距 CodePen 示例

带有 overflow:auto 和百分比高度的 div 上的滚动条

我在滚动网页中心部分时遇到了问题,而其高度需要是自动的。

这里是一个 fiddle

标题需要始终位于顶部,这意味着我不希望正文变得大于100%。

然而,#messages div 可能会变得更大,而该 div 需要自己滚动。

#messages 具有 margin-bottom,以留出空间供固定底部 div 使用。

我尝试使用box-sizing: border-box;

#messages
设置为height:100%并添加padding来固定位置,但这是一个非常糟糕的解决方案,滚动条的高度是整个页面而不仅仅是内部。

非常感谢您的任何帮助。

2个回答

6
你想要类似这个的东西。
或者可能是他的大哥
纯CSS解决方案,不需要固定任何高度。 HTML:
<div class="Container">
    <div class="First">
    </div>
    <div class="Second">
        <div class="Content">
        </div>
    </div>
</div>

CSS:

*
{
    margin: 0;
    padding: 0;
}

html, body, .Container
{
    height: 100%;
}

    .Container:before
    {
        content: '';
        height: 100%;
        float: left;
    }

.First
{
    /*for demonstration only*/
    background-color: #bf5b5b;
}

.Second
{
    position: relative;
    z-index: 1;
    /*for demonstration only*/
    background-color: #6ea364;
}

    .Second:after
    {
        content: '';
        clear: both;
        display: block;
    }

.Content
{
    position: absolute;
    width: 100%;
    height: 100%;
    overflow: auto;
}

谢谢您提供有用的代码!我想知道为什么在网上很难找到它们。 - MakuraYami

5
你可以尝试以下方法。
你的HTML代码是:
<div id="container">
    <div id="header">The header...</div>
    <div id="content">
        <div id="messages">
            <div class="message">example</div>
             ...
            <div class="message">example</div>
        </div>
        <div id="input">
            <div class="spacer">
                <input type="text" />
            </div>
        </div>
    </div>
</div>

应用以下CSS:

html, body {
    height: 100%;
}
body {
    margin:0;
}
#header {
    background:#333;
    height: 50px;
    position: fixed;
    top: 0;
    width: 100%;
}
#content {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 45px;
    overflow-y: scroll;
}
#messages {
    overflow: auto;
}
#messages .message {
    height: 79px;
    background: #999;
    border-bottom: 1px solid #000;
}
#input {
    position:fixed;
    bottom:0;
    left:0;
    width:100%;
    height: 45px;
}
#input .spacer {
    padding: 5px;
}
#input input {
    width: 100%;
    height: 33px;
    font-size: 20px;
    line-height: 33px;
    border: 1px solid #333;
    text-indent: 5px;
    color: #222;
    margin: 0;
    padding: 0;
}

请参见演示:http://jsfiddle.net/audetwebdesign/5Y8gq/ 首先,将htmlbody标签的高度设置为100%,这样您可以引用视口高度。
您希望使用position:fixed#header固定在页面顶部,同样适用于页脚#input
关键是在#content上使用绝对定位,将其拉伸到标题底部和页脚顶部之间,然后应用overflow-y:scroll以允许滚动内容(消息列表)。 评论
#input块的源代码可能放在#content块之外。

谢谢,使用我的代码示例让我选择了这个答案而不是其他的。因为我不知道哪一个是先出现的。祝你有美好的一天! - MakuraYami

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接