Search code examples
htmlcssinternet-explorer-10

Fill out the height of a variable number of child elements, when the parent element has a fixed height


I have a container element that has a fixed height. I want the child elements of this container element to completely fill the height of the container element, evenly distributing the height among the child elements. The challenge here is that the number of child elements can vary between 2 and 5 elements.

.container-element {
  height: 200px;
  border: solid black 1px;
  margin-bottom: 20px;
}

.child-element {
  background: grey;
}

.child-element:nth-child(even) {
  background: darkGrey;
}
<div class="container-element">
  <div class="child-element">
    Dummy content
  </div>
  <div class="child-element">
    Dummy content
  </div>
  <div class="child-element">
    Dummy content
  </div>
  <div class="child-element">
    Dummy content
  </div>
</div>

<div class="container-element">
  <div class="child-element">
    Dummy content2
  </div>
  <div class="child-element">
    Dummy content2
  </div>
</div>

My initial thought was to add a class to the container element that has the number of child elements that reside inside (i.e. class="container-element elements-3"), and make the height percentage of the child elements vary based on this class.

However, I was wondering if it was possible to fill the height of a parent , regardless of how many child elements exist, without having to add a different class to all the parent containers.

Sidenote: This has to work in IE10

Jsfiddle


Solution

  • This is a classic case for a flexbox. Flexbox is partially supported by IE10 using the -ms- prefix, so this should work in IE10 (I've no way to check it):

    .container-element {
      display: -ms-flexbox;
      /* TWEENER - IE 10 */
      display: flex;
      -ms-flex-direction: column;
      flex-direction: column;
      height: 200px;
      border: solid black 1px;
      margin-bottom: 20px;
    }
    
    .child-element {
      -ms-flex: auto 1;
      flex: 1;
      background: grey;
    }
    
    .child-element:nth-child(even) {
      background: darkGrey;
    }
    <div class="container-element">
      <div class="child-element">
        Dummy content
      </div>
      <div class="child-element">
        Dummy content
      </div>
      <div class="child-element">
        Dummy content
      </div>
      <div class="child-element">
        Dummy content
      </div>
    </div>
    
    <div class="container-element">
      <div class="child-element">
        Dummy content2
      </div>
      <div class="child-element">
        Dummy content2
      </div>
    </div>