首页 > 解决方案 > 在我实际设置 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元素达到全高?

标签: htmlcssflexbox

解决方案


这是由于应用于 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'。参考


推荐阅读