html - 溢出的弹性容器的孩子超过容器
问题描述
我已经有一段时间了,并尝试了很多我在不同的 Stackoverflow 问题/博客文章中看到的解决方案/......但老实说,我无法弄清楚出了什么问题。
我有一个 flexed div,里面有两个 div。顶部 div A 具有固定高度,另一个 div B 使用 填充其余部分flex: 1;
。如果屏幕调整大小并且小于 A + B 的高度,则 B 将开始溢出。我希望它滚动,但我也希望滚动时内容完全可见。出于某种我无法弄清楚的原因,内容呈现在 div B 的顶部,正如您在我的小提琴的屏幕截图中看到的那样:
以前提出的一些问题让我有所了解。例如将 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
水平时为 ),因为如果父级的顶部和子级的顶部重合并且子级更大比父母,孩子不再居中,是吗?当使用其他居中技术并且您将较大的孩子置于较小的父母中时,也会发生同样的情况。
要解决此问题,您需要防止孩子长得超过父母。
在这种情况下,这意味着.second
根据其内容 ( flex-basis: auto
) 进行大小调整,并且不允许它缩小: ( flex-shrink: 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
不适用。我希望这是有道理的,我无法更好地解释它。
推荐阅读
- tsql - TSQL 如何管理查找或处理重复项
- java - 如何通过分隔符拆分字符串?
- firefox - Firefox 开发者工具网络导出到 pcap
- python - 在 Django 中为单独的视图调用第二个 GET 请求
- python - 如何在 django CBV(基于类的视图)createviews 中上传图像
- scala - 递归函数如何在scala中返回结果?
- java - 我需要修改我的代码以在我的 POST 请求中接受多个 json 对象列表。我们如何实现这一点?任何建议都会帮助我
- google-sheets - 在 Google 表格中的 Query({Importhtml1; Importhtml2;...}) 期间丢失我的 primaryKey
- spring - Thingsboard 性能测试
- node.js - 为什么 MongoDB 在路径中添加额外的斜杠?