【问题标题】:Why inner div is not taking 100% of parent div? [duplicate]为什么内部 div 不占用父 div 的 100%? [复制]
【发布时间】:2021-10-28 14:38:50
【问题描述】:

下面的例子演示了这种奇怪的行为:outer div 有一个固定的大小,我希望 inner div 占据这个大小的 100%(即最终结果应该只是一个完全覆盖外部蓝色块的内部红色块)。

我已将 inner div 的高度设置为 100%,但其高度仍为 0px,但是,我设置的 100% 宽度正常工作,它计算为 300px,即 100 % 的父 div)。

首先,为什么 100% 高度不起作用?二、如何让100%的高度起作用?

.full {
  background: yellow;
  display: flex;
  height: 100%;
  width: 100%;
  position: absolute;
  justify-content: center;
  align-items: center;
}

.outer {
  background: blue;
  min-height: 100px;
  min-width: 300px;
}

.inner {
  background: red;
  height: 100%;
  width: 100%;
}
<div class="full">
  <div class="outer">
    <div class="inner"></div>
  </div>
</div>

【问题讨论】:

  • 将 display:grid 添加到外部或删除 height:100% 并将 display:flex 添加到外部

标签: html css layout


【解决方案1】:

在内部&lt;div&gt; 上尝试flex-grow: 1

【讨论】:

    【解决方案2】:

    当父级高度由最小高度/最大高度确定时,具有百分比高度的子级大小不正确时,这是一个错误。

    只需使用其他方法来分配高度,可以是固定的,也可以使用 flex 或其他方法。在以下示例中,我将display:flex; 添加到父级,将flex: 1; 添加到子级:

    .full {
      background: yellow;
      display: flex;
      height: 100%;
      width: 100%;
      position: absolute;
      justify-content: center;
      align-items: center;
    }
    
    .outer {
      background: blue;
      min-height: 100px;
      min-width: 300px;
      display: flex;
      flex-direction:column;
    }
    
    .inner {
      background: red;
      height: 100%;
      width: 100%;
      flex:1;
    }
    <div class="full">
      <div class="outer">
        <div class="inner"></div>
      </div>
    </div>

    注意:

    1. flex 属性是 flex-grow、flex-shrink、flex-basis 的简写属性。而设置flex: 1;实际上分配了flex-grow 1,flex-basis 0。

    2. 因为 flex-direction 默认为 row,而且我们在子元素中使用 flex: 1 并且我们需要它垂直增长(按列方向)。我们必须分配flex-direction: column;

    【讨论】:

    • 太酷了。为什么需要 flex-direction: column?
    • @user1589188 因为 flex-direction 默认为 row,并且我们在子元素中使用 flex: 1,所以我们需要它垂直增长(按列方向)。
    猜你喜欢
    • 2015-03-05
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 2021-05-14
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    相关资源
    最近更新 更多