Last Updated: February 25, 2016
· 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.

    height: $(window).height(),
    width: $(window).width()
    position: 'absolute',
    left: ($(window).width() - $('.centered-container').outerWidth())/2,
    top: ($(window).height() - $('.centered-container').outerHeight())/2


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 :

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();

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

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

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

over 1 year ago ·