html - 溢出的 flex 容器的 child 超出了容器

标签 html css flexbox

<分区>

我已经研究了一段时间,并尝试了很多我在不同的 Stackoverflow 问题/博客文章/...中看到的解决方案,但老实说,我无法弄清楚出了什么问题。

我有一个包含两个 div 的 flex div。顶部的 div A 具有固定高度,另一个 div B 使用 flex: 1; 填充其余部分。如果调整屏幕大小并且它小于 A + B 的总高度,则 B 将开始溢出。我希望它滚动,但我也希望内容在滚动时完全可见。由于某种我无法弄清楚的原因,内容呈现在 div B 的顶部之外,如您在 my fiddle 的屏幕截图中所见。 :

enter image description here

之前提出的一些问题让我有所了解。例如将 body 设置为 height: auto;,但是当我的屏幕大于 A + B 时,它就不能再居中对齐了。 min-height: 0; 在这种情况下似乎也没有帮助。

我怎样才能确保我的容器溢出但会完全显示它的内容?

最佳答案

你可以通过给出 .second 来解决这个问题:

flex-basis: auto;
flex-shrink: 0;

或者,简写:flex: 1 0 auto;

工作示例:

html, body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

body {
  display: flex;
  flex-direction: column;
}

.second {
  flex: 1 0 auto;
  background: blue;
  width: 100%;
  
  display: flex;
  justify-content: center;
  align-items: center;
  
  min-height: 0;
  
  overflow: auto;
}

.container {
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 500px;
  min-height: 0;
  /* added this to make it obvious. Obviously, not needed */
  padding: 2rem 0;
}

.container-child {
  height: 110px;
  background: green;
  width: 100%;
}

.container-child:not(:last-child) {
  margin-bottom: 30px;
}
<div class="second">
  <div class="container">
    <div class="container-child"></div>
    <div class="container-child"></div>
    <div class="container-child"></div>
  </div>
</div>

我在 .container 中添加了一些顶部和底部填充 以使其明显有效 - 但这不是必需的。

现在让我们看看为什么会发生这种情况。当你应用 .second { flex:1; 意思是:

flex-grow: 1;
flex-shrink: 1;
flex-basis: 0%;

... 这允许它的大小小于其内容。

每当您有一个较大的子级以较小的父级为中心时,浏览器将不会提供滚动条到top(或left,水平时),因为那时,如果父项的顶部和子项的顶部重合并且子项比父项大,则子项不再居中,是吗? 当使用其他居中技术并且您将较大的 child 放在较小的父项中时,也会发生同样的情况。
要解决此问题,您需要防止子级长得超过父级。

在这种情况下,这意味着根据其内容 (flex-basis: auto) 调整 .second 的大小,并且不允许它收缩:(flex-缩小:0;).

为了更好地形象化问题,请考虑以下示例:

.left, .right {
  position: relative;
  border: 1px solid red;
  padding: 1rem 5rem;
}
.left {
  left: -5rem;
}
.right {
  right: -5rem;
}
<div class="left">
  I'm taken left
</div>
<div class="right">
  I'm taken right
</div>

如果浏览器提供滚动条允许您滚动到 .left 的开头,则意味着 left: -5rem 不适用。我希望这是有道理的,我无法解释得更好。

关于html - 溢出的 flex 容器的 child 超出了容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54391073/

相关文章:

jquery - 需要视频为 3 个样式表工作 - 目前视频从较小的 div 中溢出

javascript - 无法使用 React JS 编辑输入文本

html - 我可以在 Google 云端硬盘虚拟主机中使用谷歌字体吗?

html - 如何在 HTML/CSS 中设置百分比高度值

html - 当 particles.js 库将 Canvas 附加到同一元素时,将 div 中的元素居中?

java - 如何从多个图像中获取图像ID,以使用它来获取有关图像的完整数据并在单击图像时将其显示在不同页面上

css - 用于多台服务器的 jupyter notebook 的共享配置

css - 方括号中的 "i"在 CSS 选择器中有什么作用?

html - 为什么 `min-height` 会影响 flex 布局中 div 的高度?

html - React 和 flexbox 谁能看看这个问题? flex in flex 报错