Search code examples
htmlcssvertical-alignment

Vertical Align variable height elements in fixed width container


Using display:table;, I am trying to vertically align two inline div's with different heights inside a fixed width container.

display:table; and display:table-cell with vertical-align: middle; is a very simple solution to this that works in certain circumstance - however in this it seems I have missed something.

The result of my fiddle is a correct vertical-align however each element is not holding their responsive widths to fill the entire container space. i.e. 2 elements inside the container equal 50% width.

Here is my code:

HTML

<div class="table container">
  <div class="inner-column table-cell">
    <div class="table inner-container">
        <div id="left" class="table-cell">
        content
        </div>
    </div>
  </div>
  <div class="inner-column table-cell">
    <div class="table inner-container">
        <div id="right" class="table-cell">
        content
        </div>
    </div>
  </div>
</div>

CSS

body {
  width: 100%;
  margin: 0 auto;
  background: white;
  color: white;
  text-align: center;
  background: white;
}

.table {display: table;}
.table-cell {display: table-cell; vertical-align: middle;}

.container {
  width: 600px;
  height: 200px;
  background: lightgrey;
  margin: 0 auto;
  white-space: nowrap;
  padding: 0
}

.inner-column {
  display: inline-block;
  white-space: normal;
  width: 50%;
  height: 100%;
  border:1px blue solid;
  padding: 0;
  margin: 0;
}

.inner-container {
  margin: 0 auto;
  width: 100%;
}

#left {
    background-color: red;
    height: 120px;
}

#right {
    background-color: purple;
    height: 170px;
}

Here is the above in a FIDDLE

Problem List:

  1. Width of the inner-column is slightly bigger than the container
  2. each element container is not vertically aligned to the fixed height of the container.

Solution

  • display:table-cell is not being applied since you wrote this code before display:inline-block. I have updated fiddle https://jsfiddle.net/dgzp6h2w/1/