HTML / CSS div的高度取决于其他div

时间:2016-02-19 07:21:30

标签: 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处理不断变化的高度。任何帮助或方向表示赞赏。谢谢!

4 个答案:

答案 0 :(得分:1)

为什么不使用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>

答案 1 :(得分:0)

你可以通过jquery,

来做到这一点

你必须获得每个div的高度,然后检查哪个div有最大高度。得到这个之后你必须为每个div设置这个最大高度。

在CSS中你可以定义最大高度然后溢出-y滚动。

答案 2 :(得分:0)

使用flexbox

.sidebar {
display: flex;
flex-flow: column nowrap;
}

然后,您可以修改两个子元素的flex-basis,以获得您想要的结果。

答案 3 :(得分:0)

您好,您可以试试这个CSS

.sidebar {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.child-1 {
  overflow-y: scroll;
  flex: 10 0 auto;
  min-height: 20vh;
  max-height: 80vh; // let's say the maximum height of child 1 is 80%
}

.child-2 {
  overflow-y: scroll;
  flex: 0 1 auto;
}

你应该知道flexbox仍然是一个非常新的CSS功能,所以要注意旧浏览器。

相关问题