Search code examples
htmlcsslayout

Why inner div is not taking 100% of parent div?


The example below demos this weird behaviour: the outer div has a set size and I want the inner div to take 100% of this size (i.e. the end result should be just an inner red block fully covering the outer blue block).

I have set the height of the inner div to 100% but its height is still 0px, however, the 100% width that I set is working correctly, it computes to 300px, which is 100% of its parent div).

First, why is the 100% height not working? Second, how to make the 100% height to work?

.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>


Solution

  • Its a bug when parent height is determined by min-height/max-height children with percentage heights are sized incorrectly.

    Just use some other method to assign the height, may be fixed or by using flex or whatever. In following example I added display:flex; to parent and flex: 1; to child:

    .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>

    Note:

    1. The flex property is a shorthand property for: flex-grow, flex-shrink, flex-basis. And setting flex: 1; actually assigns flex-grow 1, flex-basis 0.

    2. Since flex-direction is row by default, and since we are using flex: 1 in child elements and we need it to grow vertically (by column direction). We have to assign flex-direction: column;