0

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?

9
  • 1
    You have to add some measurement value like px or whatever. "left" : windowWidth /2 - elementWidth/2 +"px" Commented Jun 13, 2014 at 23:38
  • @Vucko, thanks for reply buto why the to setting is working fine? Commented Jun 13, 2014 at 23:40
  • 1
    Changing the positioning of an element may change its dimensions Commented Jun 13, 2014 at 23:42
  • 3
    h1 is a block element which means it will take all of the parents width, so in your example - the body width. Add h1{display:inline-block} and it will work - Fiddle Commented Jun 13, 2014 at 23:46
  • 1
    @Suffii - Vucko's answer is correct regarding the block element. 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. Commented Jun 14, 2014 at 0:01

1 Answer 1

1

On load your h1 is actually 100% wide so the Left directove is working -- it's just that's it's only indenting by 8px

Stick a h1{border: 1px solid red;} into the css of your fiddle and you'll see

Sign up to request clarification or add additional context in comments.

1 Comment

The 8px is the margin from body. Add body{margin:0} and it will be removed and the h1 will have left:0px.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.