Search code examples
htmlcssflexboxalignmentvertical-alignment

Stretch display flex or table inner divs along parent with centered texts


I'd like to create a responsive page with a fixed html structure so I can just adjust the css. I would like to create rows with vertically and horizontally centered texts. The divs should fully stretch across the parent div.

My HTML...

<body>
  <div class="parent">
    <div class="d1">
      one
    </div>
    <div class="d2">
      two
    </div>
    <div class="d3">
      three
    </div>
  </div>
</body>

My CSS...

body {
  background-color: lightyellow;
  height: 100%;
  width: 100%;
  margin: 0px;
}
.parent {
  background-color: lightblue;
  height: 100%;
}
.d1, .d2, .d3 {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  height: 100px;
}
.d2 {
  background-color: lightgreen;
}

However here I am setting d1, d2 and d3 to the height of 100px and not 100% of the parent div. Example here: https://jsfiddle.net/bLf2sxq0/

My second idea was to use display: table for the parent which results in table-rows for the childs but then I end up with the same stretching issue plus the texts are not vertically centered. Here the css would be like this ...

body {
  background-color: lightyellow;
  height: 100%;
  width: 100%;
  margin: 0px;
}
.parent {
  width: 100%;
  height: 100%;
  display: table;
  background-color: lightblue;
}
.d1, .d2, .d3 {
  text-align: center;
  height: 100px;
}
.d2 {
  background-color: lightgreen;
}

Example here: https://jsfiddle.net/qmbzkwr2/

Is there a way to stretch the divs vertically along the parent and keep the texts centered vertically and horizontally within the divs? So I would not have width 100px but something like calc(100%/3) or any other solution to do this? Or maybe by using the flex grow option? Easiest way would do it :)

Thanks for any help!


Solution

  • You're on the right track. Use flexbox to stretch and fill items vertically and evenly. Remember to set parent containers (e.g. body, html) to height: 100%.

    From here, if you want control over some items, use flex on any individual item, like flex: 1 1 300px on class .d2 for example.

    Codepen

    body, html {
      height: 100%;
    }
    
    .parent {
       background-color: lightblue;
       height: 100%;
       
       display: flex;
       flex-direction: column;
     }
    
     .d1, .d2, .d3 {
       display: flex;
       align-items: center;
       justify-content: center;
       flex: 1;
     }
    
     .d2 {
       background-color: lightgreen;
     }
      <div class="parent">
        
        <div class="d1">
          <div class="d11">
            one
          </div>
        </div>
        
        <div class="d2">
          two
        </div>
        
        <div class="d3">
          three
        </div>
        
      </div>