This code simply using a .css() in jQuery to center element is the page. This is setting the vertical centering but the horizontal (left) is not working (Please be ware that I already knew there is a text-align:center rule in CSS to to do this by element parent, but I really need to know why jquery is not doing now?!)
var elemntHeight = $("h1").height();
var elementWidth = $("h1").width();
var windowHeight = $(window).height();
var windowWidth = $(window).width();
$("h1").css({
"position" : "absolute",
"left" : windowWidth /2 - elementWidth/2,
"top": windowHeight/2 - elemntHeight /2
});
can you please let me know how to fix this?
pxor whatever."left" : windowWidth /2 - elementWidth/2 +"px"h1is a block element which means it will take all of the parents width, so in your example - thebodywidth. Addh1{display:inline-block}and it will work - Fiddleblockelement. By defining position:absolute in your CSS, the script evaluates WITHOUT the full width of its parent (because it's been removed from the DOM flow due to positioning) - otherwise, it uses 100% of the width.