Search code examples
htmlcsscentering

Vertical align middle table cell responsive with text


I want to centre content in a div using the table approach --- see first section here

This is all good, however I have an issue.

I have 2 divs, each taking up 50% width. The left div contains an image which is px` in length. The right div contains text. I can set a height to the div containing the text and it works, however, when I make the screen smaller it is not responsive. Can anyone tell me, if there is one, the technique to decrease the height of the div with the text in it as the screen reduces in size?

I want to retain the 2 divs side by side, and reduce the height of the div on the right as the screen gets smaller, at the same rate that the image on the right decreases in size.

See jsfiddle HERE and code below to demonstrate:

HTML

<div class="left">
   <img src="http://www.profightdb.com/img/wrestlers/thumbs-600/1414330df8brethart.jpg">
</div>

<div class="right">
  <div class="table">
    <div class="table-cell">
      <p>Test</p>
      <p>Lorem ipsu se skio sas nie lorem dtakorem ipsu se skio sas nie lorem dtak lorem ipsu se skio sas nie lorem dtak</p>
    </div>
  </div>
</div>

CSS

img {
  width: 100%;
}

.left, .right {
  float: left;
  width: 50%;
}

.table {
  height: 400px;
  display: table;
}

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

Solution

  • I updated your fiddle: https://jsfiddle.net/9bjan951/4/

    Basically what I've done:

    • Added a wrapper-element
    • Clear the floating, so the wrapper gets a height
    • Set the right column to absolute position and give it always 100% height of its parent
    • Set the right table to 100% height
    • For narrow screens the text will overflow with a scrollbar

    Most of the magic happens here:

    .right {
      height: 100%;
      background: #c54a8d;
      position: absolute;
      top: 0;
      left: 50%;
      right: 0;
      bottom: 0;
      overflow: hidden;
      overflow-y: auto;
    } 
    

    I hope this helps.