Skip to content

Instantly share code, notes, and snippets.

@martynchamberlin
Created September 16, 2014 02:32
Show Gist options
  • Save martynchamberlin/1bfdc3c1627a77833c0d to your computer and use it in GitHub Desktop.
Save martynchamberlin/1bfdc3c1627a77833c0d to your computer and use it in GitHub Desktop.
centerVertically.js—a simple extension to the jQuery library that allows you to vertically center most anything.
/**
* centerVertically() takes a given DOM element and centers
* it vertically within the parent element. If the height
* of the browser is less than this element's height, then
* the original margin relative to top is restored until
* the window gets larger again.
*
* Note that this function extends the jQuery library and
* therefore requires it before this function can be
* defined.
*
* E.g. usage:
* $('.wrap').centerVertically();
*/
(function( $ ){
$.fn.centerVertically = function() {
var elem = $(this);
var height = $(elem).outerHeight();
var marginTop = $(elem).css('marginTop');
var adjustMargin = function() {
if ( $(window).height() > height )
{
$(elem).css('margin-top', ( $(window).height() - height ) / 2 + 'px');
}
else
{
$(elem).css('margin-top', marginTop);
}
}
adjustMargin();
$(window).resize( adjustMargin );
};
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment