Last active
December 13, 2015 18:08
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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