Center DIV vertically and horizzontally with Jquery

Center DIV vertically and horizzontally with Jquery

by Marco Marcoaldi

HTML

<div id="test" class="centered">Centered</div>

CSS

.centered{
    background-color:#cdcdcd;    
}

JavaScript

$(document).ready(function(){
						   
 $(window).resize(function(){

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

});