为什么高度= 100%不起作用?

米莎·莫罗什科(Misha Moroshko)

我使用占用所有可用空间的第三方组件,即width=100%height=100%我没有控制权。

我正在尝试使其适合以下布局,但是它height=100%不起作用(我希望第三方组件占据所有绿色空间)。

在此处输入图片说明

为什么?您将如何解决?

.container {
  display: flex;
  flex-direction: column;
  width: 200px;
  height: 100px;
}

.header {
  display: flex;
  background-color: rgba(255, 0, 0, 0.5);
}

.content {
  flex-grow: 1;
  background-color: rgba(0, 255, 0, 0.5);
}

.third-party-component {
  height: 100%;
  width: 100%;
  background-color: rgba(0, 0, 255, 0.5);
}
<div class="container">
  <div class="header">Header</div>
  <div class="content">
    <div class="third-party-component">
      Third party component
    </div>
  </div>
</div>

一个儿子

通常,对于使用percent onheight来获取其父代的高度的元素,父代需要的高度auto必须不是或位于绝对高度,否则height将被计算为auto

基于这两个选项,并且正如您在评论中提到的那样,您自己的标题的高度是动态的,您将得到绝对定位。

将绝对值添加到的问题content将被淘汰,并且不再表现为正常流动的flex项目,这是一个好消息,可以将包装器设置为绝对值。

堆栈片段

.container {
  display: flex;
  flex-direction: column;
  width: 200px;
  height: 100px;
}

.header {
  display: flex;
  background-color: rgba(255, 0, 0, 0.5);
}

.content {
  position: relative;                               /*  added  */
  flex-grow: 1;
  background-color: rgba(0, 255, 0, 0.5);
}

.wrapper {
  position: absolute;                               /*  added  */
  left: 0;                                          /*  added  */
  top: 0;                                           /*  added  */
  right: 0;                                         /*  added  */
  bottom: 0;                                        /*  added  */
}

.third-party-component {
  height: 100%;
  width: 100%;
  background-color: rgba(0, 0, 255, 0.5);
}
<div class="container">
  <div class="header">Header</div>
  <div class="content">
    <div class="wrapper">
      <div class="third-party-component">
       Third party component
      </div>
    </div>
  </div>
</div>


另一个选择可能是更新Flexbox属性,content使用flex: 1 1 100%,给定高度,使用高度高度,header flex-shrink: 0;以使其不会收缩(达到content100%)。

不过,这可能无法在Safari上使用,因为我知道height未设置属性时会遇到问题,但由于无法访问Safari,现在无法测试。

.container {
  display: flex;
  flex-direction: column;
  width: 200px;
  height: 100px;
}

.header {
  display: flex;
  flex-shrink: 0;
  background-color: rgba(255, 0, 0, 0.5);
}

.content {
  flex: 1 1 100%;
  background-color: rgba(0, 255, 0, 0.5);
}

.third-party-component {
  height: 100%;
  width: 100%;
  background-color: rgba(0, 0, 255, 0.5);
}
<div class="container">
  <div class="header">Header</div>
  <div class="content">
    <div class="third-party-component">
      Third party component
    </div>
  </div>
</div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章