Skip to content

Instantly share code, notes, and snippets.

@kalenjohnson
Forked from drrobotnik/html
Created July 10, 2014 00:17
Show Gist options
  • Save kalenjohnson/70427ecdec88d73ace0b to your computer and use it in GitHub Desktop.
Save kalenjohnson/70427ecdec88d73ace0b to your computer and use it in GitHub Desktop.
<style>
.t{ display:table; }
.cell{ display: table-cell; width:100%;height:100%;vertical-align: middle; }
</style>
<div class="t" data-ratio='1:1' data-mobile-ratio='3:1'>
<div class="cell">here be some perfectly centered content regardless of text length</div>
</div>
jQuery(document).ready(function($) {
$(window).on('load resize orientationchange',aspectRatioRespond);
aspectRatioRespond();
});
function aspectRatioRespond(){
mobileMax = 480;
elements = jQuery('[data-ratio]');
elements.each(function(){
container = jQuery(this);
var elRatio = container.data('ratio');
var elLineHeight = ( typeof container.data('ratio-text') == 'boolean' ) ? container.data('ratio-text') : 0;
var elMobileRatio = ( typeof container.data('mobile-ratio') == 'string' ) ? container.data('mobile-ratio') : container.data('ratio');
if(container.width() < mobileMax){
autoHeight = elMobileRatio;
}else{
autoHeight = elRatio;
}
ratio = autoHeight.match(/(\d+)\:(\d+)/);
ratio = ratio[1] / ratio[2];
container.height( container.width() / ratio );
if( elLineHeight )
container.css( {'line-height': (container.width() / ratio)+'px' } );
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment