Scrollbar without fixed height/Dynamic height with scrollbar

GuillaumeS picture GuillaumeS · Jun 11, 2012 · Viewed 96k times · Source

I have this HTML structure:

<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>

I want to have the three parts inside the main part (#body) without overflow. So I need a scroll bar in the middle part.

I tried this CSS:

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

And this:

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

But neither of them work.

I made an example at JSFiddle.

Can I do this with only CSS and HTML? I'd prefer to avoid Javascript.

Answer

mtyaka picture mtyaka · Aug 24, 2016

Flexbox is a modern alternative that lets you do this without fixed heights or JavaScript.

Setting display: flex; flex-direction: column; on the container and flex-shrink: 0; on the header and footer divs does the trick:

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;
}