div 的 HTML/CSS 高度依赖于其他 div

标签 html css scroll height overflow

我正在尝试构建一个占据浏览器 100% 高度的侧边栏。在这个侧边栏中,有两个 div,它们的大小会根据里面的内容而改变。

<div class="sidebar">
  <div class="child-1"></div>
  <div class="child-2"></div>
</div>

http://i.imgur.com/LIPLo4K.png (对不起,我尽力展示了一个例子)

如您所见,侧边栏以 child-2 开始,占据了大约 80% 的高度(即使其内容没有填满 div)和 child- 1 只占高度的20%左右。但是,随着 child-1 内容的增长,child-2 会变小。如果 child-2 的内容溢出,我可能会使用 overflow-y: scroll 来包含它的内容。同样,一旦 child-1 达到 max-height,我希望它也能够垂直滚动。

我不太清楚如何做到这一点并仅使用 CSS 来处理不断变化的高度。任何帮助或指导表示赞赏。谢谢!

最佳答案

为什么不使用 flex

body{ margin: 0; }
.sidebar{
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.child-1{
  background-color: #8989Ef;
}
.child-2{
  background-color: #EF8989;
  flex: 1;
}
<div class="sidebar">
  <div class="child-1">
    <p>this is content</p>
    <p>this is content and this content is long</p>
    <p>this is content</p>
    <p>this is content and this content is long</p>
  </div>
  <div class="child-2"></div>
</div>

关于div 的 HTML/CSS 高度依赖于其他 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35499595/

相关文章:

javascript - Rails 文本区域保存到数据库然后显示

javascript - bootstrap 组件的导航侧边栏 + 动画部分指示器

javascript - 通过滚动到页面的不同部分来更改导航

scroll - 了解滚动深度报告

javascript - 使用Javascript控制表格单元格的内部文本

html - 在 HTML 中,同时使用内联样式表和外部样式表是一种好习惯吗?

javascript - 当(仅)使用模板系统时,我应该如何管理子模板的 CSS、javascript 等?

javascript - 如果用户在没有滚动条的情况下使用滚轮滚动则触发

html - Div 不会使用 CSS 达到 100% 高度

css - Angular:primeng 的样式无法工作,即使它们列在 styles.scss 中