I am using this script to center my div horizontally and vertically.
When the page loads the div gets centered vertically, not horizontally until I resize the browser.
What am I doing wrong?
$(document).ready(function (){
$(window).resize(function (){
$('.className').css({
position:'absolute',
left: ($(window).width() - $('.className').outerWidth())/2,
top: ($(window).height() - $('.className').outerHeight())/2
});
});
$(window).resize();
});
I normally use this "technique":
UPDATE:
I’m updating the solution, as suggested by the user Fred K, using
.outerWidth()and.outerHeight()to have a more precise centering.Some additional notes from jQuery’ documentation (
.outerWidth(),.outerHeight()):UPDATE 2:
A simple update to show how you could use
thisinside thecss()method in case there are more elements with the sameclasstag with different sizes.