首页 > 解决方案 > 如何在高度未知的div上设置溢出滚动

问题描述

我有以下设置:

.page {
  width: 360px;
height: 704px;
border: 1px solid red;
}

header {
  height: 10%;
  width: 100%;
  display: flex;
  align-items: center;
justify-content: center;
  background-color: lightblue;
}

main {
  height: 90%;
  background-color: beige;
  width: 100%;
  
  display: flex;
  flex-flow: column;
}

.container-dynamic {
  width: 100%;
  height: 400px;
  border: 1px dashed grey;
  
  display: flex;
  align-items: center;
  justify-content: center;
  
  flex: 0 0 auto;
}

p {
  text-aling: center;
}

.container-fill {
  width: 80%;
  
  border: 1px dashed black;
  
  height: auto;
  
  flex: 1 1 auto;
  
  
}

.c {
  width: 100%;
  background-color: lightgreen;
  padding: 10px;
  
  max-height: 100%;
  
  overflow: scroll;
  
  flex: 1 1 auto;
}

.b {
  width: 80%;
  height: 200vh;
  background-color: lightblue;
}
<div class="page">
  <header>
    HALLO
  </header>
  <main>
    <div class="container-dynamic">
      <p>This container has dynamic height</p>
    </div>
    <div class="container-fill">
      <p>This container fills up the left space</p>
      <div class="c">
        <div class="b">
        </div>
      </div>
    </div>
  </main>
</div>

现在如您所见,绿色区域比整个.page元素大得多。我想要实现的是让绿色区域填充页面上的左侧空间。我通过flex: 1 1 autoon.c和 with display: flex, flex-flow: columnonmain元素实现了这一点。除此之外,我需要绿色区域是可滚动的,当孩子(这里是浅蓝色矩形.b)太大而无法容纳它而不会溢出时。但是overflow: scroll在绿色元素上设置没有任何影响并导致给定的代码示例。如果有人可以帮助我了解如何实现我的目标,我将不胜感激。


当然,这可以通过 JavaScript 计算剩余高度来实现,但我想知道是否也有一个 css-only 方法。

标签: javascripthtmlcssoverflow

解决方案


.page {
  width: 360px;
height: 704px;
border: 1px solid red;
}

header {
  height: 10%;
  width: 100%;
  display: flex;
  align-items: center;
justify-content: center;
  background-color: lightblue;
}

main {
  height: 90%;
  background-color: beige;
  width: 100%;
  
  display: flex;
  flex-flow: column;
}

.container-dynamic {
  width: 100%;
  height: 400px;
  border: 1px dashed grey;
  
  display: flex;
  align-items: center;
  justify-content: center;
  
  flex: 0 0 auto;
}

p {
  text-aling: center;
}

.container-fill {
  width: 80%;
  
  border: 1px dashed black;
  
  height: 100%;
  
  flex: 1 1 auto;
  
  
}

.c {
  width: 100%;
  background-color: lightgreen;
  padding: 10px;
  
  max-height: 100%;
  
  overflow: scroll;
  
  flex: 1 1 auto;
  box-sizing: border-box;
}

.b {
  width: 80%;
  height: 200vh;
  background-color: lightblue;
}

.scroll-elem-container {
  flex-grow: 1;
  overflow: hidden;
}
<div class="page">
  <header>
    HALLO
  </header>
  <main>
    <div class="container-dynamic">
      <p>This container has dynamic height</p>
    </div>
    <div class="scroll-elem-container">
      <div class="container-fill">
        <div class="c">
          <div class="b">
          </div>
        </div>
      </div>
    </div>
  </main>
</div>


推荐阅读