【问题标题】:I want to add scroll for child div without setting any height when its overflow the parent div当子div溢出父div时,我想为子div添加滚动而不设置任何高度
【发布时间】:2014-11-11 14:10:58
【问题描述】:

我想在底部子 div 溢出父级时添加滚动。我不想为顶部和底部 div 设置任何高度。它必须计算父级的剩余高度,并且它应该只在底部 div 中显示滚动

#parent{
    height:100px;
    width:100px;
    border: 1px solid red;
}

#top{
    background-color: #CCC;
    width:100%;  
    height:auto
}

#bottom{
    height: auto;
    width: 100%;
    background-color: grey;
    overflow-y:auto;
}
<div id="parent">
    <div id="top">
        top content
        no need of scroll
    </div>
    <div id="bottom">
        I need scroll here when
        this content overflow the parent.        
    </div>
</div>

【问题讨论】:

    标签: html css scroll


    【解决方案1】:

    您可以使用 flexbox 来实现:

    • display: flex; 添加到#parent
    • flex-direction: column;添加到#parent以设置方向
    • flex: 1; 添加到#bottom 以占用所需空间

    #parent{
        height:100px;
        width:100px;
        border: 1px solid red;
        display: flex;
        flex-direction: column;
    }
    
    #top{
        background-color: #CCC;
        width:100%;  
        height:auto
    }
    
    #bottom{
        height: auto;
        width: 100%;
        background-color: grey;
        overflow-y:auto;
        flex: 1;
    }
    <div id="parent">
        <div id="top">
            top content
            no need of scroll
        </div>
        <div id="bottom">
            I need scroll here when
            this content overflow the parent.        
        </div>
    </div>

    【讨论】:

    • 所有浏览器都支持吗?
    • @SatheeshSurendar 几乎所有现代浏览器。链接:caniuse.com/#feat=flexbox
    • @mgibala 打败了我!除了旧版本的 IE 之外,对 flexbox 的支持还不错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2017-02-11
    相关资源
    最近更新 更多