How to make a scrollable element fill 100% of the remaining height of a parent element?

前端 未结 3 1469
旧巷少年郎
旧巷少年郎 2021-01-14 09:15

I have a container div that is a fixed height. It has some content and another child element. I would like the child element to scroll when it has filled the remaining heigh

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-14 09:53

    Are you looking for this: Fiddle

    I think this is only possible if you set the height of #body. Else it just flows, overflow: scroll on it or overflow: hidden on #container has no effect. And to set its height, you have to know/set the height of #titlebar.

    I think jQuery can solve this height problem easily.

    CSS

    #container {
        height: 250px;
        border: solid;
        /*overflow: hidden*/ /* <-- not really needed if height of sub-elements*/
                             /* is <= child of container */
    }
    #titlebar {
        height: 60px;
        background: gray;
    }
    #body {
        height: 190px;
        overflow-y: scroll;
    }
    

    EDIT

    I think making a block element the height remaining is not possible by just CSS as elements take as much height they need and not as much height available, unless specified.

    If you can use script, see this fiddle

    jQuery

    var $body = $('div#body');
    var h = $body.parent('div').height()
            - $body.siblings('div#titlebar').height();
    $body.height(h);
    

    CSS

    #container {
        height: 250px;
        border: solid;
        overflow: hidden
    }
    #titlebar {
        background: gray;
    }
    #body {
        overflow-y: scroll;
    }
    

提交回复
热议问题