jquery – center a div on the screen

A simple method to vertically align a block item using jQuery. If you want to fix the position just pas position:’fixed’.

<script type="text/javascript">
(function($){
$.fn.extend({
center: function () {
return this.each(function() {
var top = ($(window).height() - $(this).outerHeight()) / 2;
var left = ($(window).width() - $(this).outerWidth()) / 2;
$(this).css({position:'absolute', margin:0, top:
(top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
 });
 }
    });
})(jQuery);
$(function(){
$('#centerDiv').center();
});
</script>
Share this nice post: