Last Updated: February 25, 2016
·
1.142K
· xphong

Perfectly Center Inside Entire Page with jQuery

Set the outer container's height and width to the window's height and width.

Set the inner container's absolute positioning according to the outer container's height and width.

$(window).resize(function(){
  $('.container').css({
    height: $(window).height(),
    width: $(window).width()
  });
  $('.centered-container').css({
    position: 'absolute',
    left: ($(window).width() - $('.centered-container').outerWidth())/2,
    top: ($(window).height() - $('.centered-container').outerHeight())/2
  });
});

$(window).resize();

Put the script inside window resize so that whenever the user resizes the window, the container stays centered.

Call window resize on load for initial centering.

2 Responses
Add your response

You might want to debounce it using lodash, undescore or jQuery debounce plugin from Paul Irish : http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/

Nice anyway !

over 1 year ago ·

instead of calling jQuery you should cache these elements outside your resize event handler. traversing a large dom might be inefficient so doing it only once might improve the performance!

var $window = $(window);
var $container = $('.container');
var $centerContainer = $('.centered-container');
// you should also cache the size of the centered container if its size never changes
// var centerContainerWidth = $centerContainer.outerWidth();
// var centerContainerHeight = $centerContainer.outerHeight();

$window.resize(function(){
  var windowWidth = $window.width();
  var windowHeight = $window.height();

  $container .css({
    height: windowHeight,
    width: windowWidth 
  });

  $centerContainer.css({
    position: 'absolute',
    left: (windowWidth - $centerContainer.outerWidth()) / 2,
    top: (windowHeight - $centerContainer.outerHeight()) / 2
  });
});

$window.resize();
over 1 year ago ·