Skip to content

Instantly share code, notes, and snippets.

@Fab1en
Last active December 13, 2015 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fab1en/4952618 to your computer and use it in GitHub Desktop.
Save Fab1en/4952618 to your computer and use it in GitHub Desktop.
How to vertically and horizontally align any block element on the screen with Javascript
// vertically and horizontally center a block on the browser screen
function centerBlock ($block){
var top = Math.floor(($(window).height() - $block.height())/2);
var left = Math.floor(($(window).width() - $block.width())/2);
$block.css('margin', top+'px '+left+'px');
}
// use it
centerBlock($('.myblock'));
$(window).resize(function(){
centerBlock($('.myblock'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment