Search code examples
htmltwitter-bootstrapcssvertical-alignment

Vertically centering content in an element with no height, but padding


Fiddle: http://jsfiddle.net/dbwvx42s

Description of Issue: I'm using Bootstrap to make some columns within a section. The section has zero height (e.g. height: 0) but 56.25% bottom padding in order to maintain the aspect ratio (16:9) of the other content on the page.

The problem I'm running into is how to vertically center the content within this zero-height, padded element. I've attempted a flexbox solution to no avail. I've tried inline-blocking the content and using vertical-align, which was also a no-go. I'm running out of tricks!

Any help appreciated.

Code:

#section-1 {
    background-color: #0099cc;
    color: #fff;
    height: 0;
    padding-bottom: 56.25%;
}

Solution

  • You can create an absolutely positioned child element containing the content:

    #section-1 {
      
      position: relative;
      
      background-color: #0099cc;
      color: #fff;
      height: 0;
      padding-bottom: 56.25%;
    }
    
    #section-1 div.content {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      
    }
    <div id="section-1">
      <div class="content">
        Content goes here  
      </div>
    </div>

    Now, div.content can be used as a normal sized div.