【问题标题】:Flexbox overflow when the container reach minimum size当容器达到最小尺寸时 Flexbox 溢出
【发布时间】:2016-11-16 14:14:51
【问题描述】:

我有一个 flex 列容器,里面有 2 个 div。第一个 div 有 flex: 1 以使其与剩余空间一起增长。第二个 div 有一个固定的高度。请注意,容器位于占据整个视口的固定 div 内。

问题是当容器太小放不下内容时,第一个div的内容在第二个下面溢出。

.test {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background-color: red;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  //min-height: 500px;
}
.child1 {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}
.child2 {
  width: 100%;
  display: flex;
  justify-content: center;
}
span {
  padding: 20px;
}
span:first-child {
  margin-top: auto;
}
span:last-child {
  margin-bottom: auto;
}
<div class="test">
  <div class="child1">
    <span>Test1</span>
    <span>Test2</span>
    <span>Test3</span>
    <span>Test4</span>
    <span>Test5</span>
    <span>Test6</span>
    <span>Test7</span>
    <span>Test8</span>
  </div>
  <div class="child2">
    <span>Test1</span>
    <span>Test2</span>
    <span>Test3</span>
    <span>Test4</span>
  </div>
</div>

这是codepen example

一种解决方案可能是在容器上设置一个最小高度,但这不是一个动态和响应式的解决方案。

谁能告诉我当整个内容不适合时如何在容器上实现溢出行为?

【问题讨论】:

标签: html css overflow flexbox


【解决方案1】:

您可以将overflow:auto 添加到.test 并在.child1 上更新flex 值:DEMO to play with

.test {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background-color: red;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow:auto;/* update */
}

.child1 {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content:center;/* update (IE)*/
  flex: 1 0 auto;/* update *//* flex-shrink:0 allow element to expand and push next container else overflow defaut  is visible IF SET TO 1 */
}

.child2 {
  width: 100%;
  display: flex;
  justify-content: center;
}

span {
  padding: 20px;
}

span:first-child {
  margin-top: auto;
}

span:last-child {
  margin-bottom: auto;
}
<div class="test">
  <div class="child1">
    <span>Test1</span>
    <span>Test2</span>
    <span>Test3</span>
    <span>Test4</span>
    <span>Test5</span>
    <span>Test6</span>
    <span>Test7</span>
    <span>Test8</span>
  </div>
  <div class="child2">
    <span>Test1</span>
    <span>Test2</span>
    <span>Test3</span>
    <span>Test4</span>
  </div>
</div>

【讨论】:

  • 按预期工作,谢谢!你能编辑你的答案来解释为什么flex-shrink: 0 解决了这个问题吗?
  • @Simon 更新了 CSS 注释 /*flex-shrink:0 允许元素展开并推送下一个容器,否则溢出默认可见 IF SET TO 1 */
猜你喜欢
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
  • 1970-01-01
  • 2023-04-10
相关资源
最近更新 更多