一尘不染

没有固定高度的滚动条/带有滚动条的动态高度

css

我有这个HTML结构:

<div id="body">
    <div id="head">
        <p>Dynamic height without scrollbar</p>
    </div>
    <div id="content">
        <p>Dynamic height with scrollbar</p>
    </div>
    <div id="foot">
        <p>Fixed height without scrollbar</p>
    </div>  
</div>

我想在主体部分(#body)中包含三个部分而不会溢出。因此,我需要在中间部分使用滚动条。

我尝试了这个CSS:

#content{
    border: red solid 1px;
    overflow-y: auto;
}

和这个:

#content{
    border: red solid 1px;
    overflow-y: auto;
    height: 100%;
}

但是它们都不起作用。

我在JSFiddle上做了一个例子。

我可以仅使用CSS和HTML来做到这一点吗?我宁愿避免使用Javascript。


阅读 221

收藏
2020-05-16

共1个答案

一尘不染

Flexbox是一种现代替代方案,可让您无需固定高度或JavaScript即可执行此操作。

设置display: flex; flex-direction: column;在容器上,并flex-shrink: 0;在页眉和页脚的div的伎俩:

HTML:

<div id="body">
    <div id="head">
        <p>Dynamic size without scrollbar</p>
        <p>Dynamic size without scrollbar</p>
        <p>Dynamic size without scrollbar</p>  
    </div>
    <div id="content">
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
    </div>
    <div id="foot">
        <p>Fixed size without scrollbar</p>
        <p>Fixed size without scrollbar</p>
    </div>  
</div>

CSS:

#body {
    position: absolute;
    top: 150px;
    left: 150px;
    height: 300px;
    width: 500px;
    border: black dashed 2px;
    display: flex;
    flex-direction: column;
}

#head {
    border: green solid 1px;
    flex-shrink: 0;
}

#content{
    border: red solid 1px;
    overflow-y: auto;
    /*height: 100%;*/
}

#foot {
    border: blue solid 1px;
    height: 50px;
    flex-shrink: 0;
}
2020-05-16