html - 在我实际设置 height: 100% 之前,相对 div 的高度为 100%
问题描述
设置
.container {
position: relative;
display: flex;
flex-direction: row;
justify-content: flex-start;
flex: 1 1;
padding: 28px;
width: 100%;
background-color: #eee;
}
.bar {
position: relative;
width: 5px;
background-color: blue;
}
<div class="container">
<div class="bar"></div>
<div>
lskdjf
</div>
</div>
请注意,蓝色条达到容器的完整高度,减去填充。
但是,如果我添加height: 100%
到.bar
课程中,高度就会消失。
.bar {
position: relative;
width: 5px;
background-color: blue;
height: 100%;
}
问题
我想实际上将高度设置为 100% 会使浏览器感到困惑,因为父级实际上并没有设置高度,但是什么属性 pre-setting-height-to-100% 允许高度为 100%?而且,鉴于这实际上是我的目标,不指定 100% 是否“正确”,还是有更好的方法来确保.bar
元素达到全高?
解决方案
这是由于应用于 flexbox 容器的拉伸默认对齐方式使所有元素都被拉伸以适应其父级高度。
.container {
position: relative;
display: flex;
flex-direction: row;
justify-content: flex-start;
flex: 1 1;
padding: 28px;
width: 100%;
background-color: #eee;
}
.bar {
position: relative;
width: 5px;
background-color: blue;
}
<div class="container">
<div class="bar"></div>
<div>
lskdjf
</div>
</div>
如果 flex 项的 cross size 属性计算为 auto,并且两个交叉轴边距都不是 auto ,则 flex 项被拉伸。它的使用值是使项目的边距框的交叉大小尽可能接近与线相同的大小所需的长度,同时仍然尊重由 min-height/min-width/max-height/max- 施加的约束宽度。参考
如果您更改对齐方式,这将不再发生
.container {
position: relative;
display: flex;
flex-direction: row;
justify-content: flex-start;
flex: 1 1;
padding: 28px;
width: 100%;
background-color: #eee;
align-items:flex-start;
}
.bar {
position: relative;
width: 5px;
background-color: blue;
}
<div class="container">
<div class="bar"></div>
<div>
lskdjf
</div>
</div>
如果您设置任何高度值,考虑到上述规范,尺寸将不再是自动的,因此拉伸将不再适用,您将陷入百分比高度问题,这将使高度下降到自动,因为父高度是没有明确设置。
指定百分比高度。该百分比是相对于生成框的包含块的高度计算的。如果包含块的高度没有明确指定(即,它取决于内容高度),并且该元素不是绝对定位的,则该值计算为'auto'。参考
推荐阅读
- python - Python/Kivy 中的 __init__ 参数
- sql - 如何在sql中的所有客户的单独列中查找最后一个和倒数第二个记录
- linux - “service apache2 reload”和“sudo systemctl restart apache2”有什么区别?
- batch-file - 如何仅复制文件夹中的目录及其内容并使用批处理排除 0 级文件?
- python - 子函数的 Python 装饰器
- routes - 环回应用程序无法验证链路
- c# - 如何修复此错误:C# 中的 System.UnauthorizedAccessException?
- php - 如何修复使用 api 发送到 php 的变量的空结果?
- reactjs - CommonJS 要求与 ES6 导入差异
- python - 从 Python 中的随机目录中读取文本文件中的数据