html - 当它溢出父 div 时,我想为子 div 添加滚动而不设置任何高度

标签 html css scroll

当它溢出父级时,我想在底部子级 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>

最佳答案

您可以使用 flexbox 实现此目的:

  • display: flex;添加到#parent
  • #parent中添加flex-direction: column;设置方向
  • 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>

关于html - 当它溢出父 div 时,我想为子 div 添加滚动而不设置任何高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26866832/

相关文章:

javascript - 通过 javascript 更改 html DOM 没有响应

CSS3 动画应该停在位置 75%

javascript - 使用多个单选按钮验证多个选项卡

javascript - 使用轮播滑动图像

javascript - CSS视差标题和粘性导航相互排斥?

php - 使用PHP进行网站爬取

javascript - 从多维数组中的每个索引中删除最后 2 个元素

javascript - Web 服务器上的 html 页面的 XMLHttpRequest 但不在开发中

android - 滚动 ListView 时出现内存不足异常?

css - 无法一直滚动到 div 的底部