【问题标题】:Height of relative div is 100% until I actually set height: 100%在我实际设置 height: 100% 之前,相对 div 的高度为 100%
【发布时间】:2020-07-22 08:54:54
【问题描述】:

设置

.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 元素达到完整高度?

【问题讨论】:

  • 该栏消失,因为其中没有内容。 bar到底应该做什么?
  • jsFiddle 被我屏蔽了。请在您的问题中输入minimal reproducible example
  • @ElmanHuseynov 该栏实际上有一个绝对定位的可点击面板,但它似乎与手头的问题无关。
  • @j08691,看起来有人在这方面打败了我。谢谢 Azametzin,我一定会为以后的问题这样做。
  • 这是因为高度是相对于 div 内元素的高度

标签: html css flexbox


【解决方案1】:

这是由于应用于 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- 施加的约束宽度。 ref

如果您更改对齐方式,则不会再发生这种情况

.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 因为没有明确设置父高度。

指定百分比高度。百分比是相对于生成框的包含块的高度计算的。如果包含块的高度没有明确指定(即,它取决于内容高度),并且该元素不是绝对定位的,则该值计算为“自动”。 ref

【讨论】:

  • 谢谢 Temani!这是信息性的 - 假设我确实想指定默认值以外的对齐方式,比如align-items: flex-start?正如预期的那样,当我在父级上设置它时,蓝线消失了。将高度设置为父高度的正确方法是什么?
  • @wheresmycookie 要么通过添加 align-self: stretch; 来调整元素的对齐方式,要么您需要考虑 position: absolute 就可以了
猜你喜欢
  • 2015-03-17
  • 2012-12-22
  • 1970-01-01
  • 2013-07-18
  • 2012-07-24
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
相关资源
最近更新 更多