Flexbox调整大小并滚动可溢出

时间:2019-03-22 16:00:29

标签: html css css3 flexbox

我有正在调整大小的内容,并且我想要一个固定的标题,该标题不会增长/缩小,也不属于可滚动内容。如果没有足够的空间,则下面的内容将变为可滚动。

内容外部包装(flexGrowWrapper)具有flex-grow: 1,而内部包装具有height: 100%; overflow-y: auto。这里的思考过程是flexGrowWrapper将填满resize div中的所有剩余空间,然后内部包装将占据flexGrowWrapper的整个高度,如果有溢出,则应该滚动。

正在发生的事情是flexGrowWrapper确实增长到可以填充resize区域,但是似乎它的内容表明它是最小高度。

如何使flexGrowWrapper永远不会超出resize区域的高度?

$("button").click(function() {
	$(".resize").toggleClass("small");
});
.resize {
  height: 200px;
  display: flex;
  flex-direction: column;
  overflow-y: hidden;
  width: 300px;
}

.resize.small {
  height: 100px;
}

.heading {
  flex: 0 0 auto;
}

.flexGrowWrapper {
  border: 2px solid red;
  flex-grow: 1;
}

.wrapper {
  height: 100%;
  overflow-y: auto;
}

.content {
  display: flex;
  flex-direction: row;
  clear: both;
}
<button>
Resize
</button>
<div class="resize">
  <div class="heading">
  <label>Some heading that wont scroll</label>
  </div>
  <div class="flexGrowWrapper">
    <div class="wrapper">
      <div class="content">
        content
      </div>
      <div class="content">
        content
      </div>
      <div class="content">
        content
      </div>
      <div class="content">
        content
      </div>
      <div class="content">
        content
      </div>
      <div class="content">
        content
      </div>
      <div class="content">
        content
      </div>
    </div>
  </div>
</div>
<div>
 Something else here
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

注意:我看过this similar question,但似乎有一些不同,我无法找到适合我的解决方案。

1 个答案:

答案 0 :(得分:0)

min-height: 0添加到.flexGrowWrapper-请参见下面的演示

$("button").click(function() {
  $(".resize").toggleClass("small");
});
.resize {
  height: 200px;
  display: flex;
  flex-direction: column;
  overflow-y: hidden;
  width: 300px;
}

.resize.small {
  height: 100px;
}

.heading {
  flex: 0 0 auto;
}

.flexGrowWrapper {
  border: 2px solid red;
  flex-grow: 1;
  min-height: 0; /* ADDED */
}

.wrapper {
  height: 100%;
  overflow-y: auto;
}

.content {
  display: flex;
  flex-direction: row;
  clear: both;
}
<button>
Resize
</button>
<div class="resize">
  <div class="heading">
    <label>Some heading that wont scroll</label>
  </div>
  <div class="flexGrowWrapper">
    <div class="wrapper">
      <div class="content">
        content
      </div>
      <div class="content">
        content
      </div>
      <div class="content">
        content
      </div>
      <div class="content">
        content
      </div>
      <div class="content">
        content
      </div>
      <div class="content">
        content
      </div>
      <div class="content">
        content
      </div>
    </div>
  </div>
</div>
<div>
  Something else here
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


为什么有效

请注意,这是因为对于列flexbox ,默认的min-height值为auto(沿着 flex轴)。您可以在下面看到这种行为的一些示例: