0

I would like to do something like this, but it's doesn't work

 window.onresize = center;

 function center() 
 {
      var x=window.innerWidth;
      x = x/2;
      document.getElementById("center_div").style.marginLeft = x;
 }

How can I do it?

3
  • 1
    Please define what "doesn't work" means. Commented Apr 10, 2013 at 1:11
  • What are you trying to do with your code? Can you explain it? Commented Apr 10, 2013 at 1:14
  • as far as I know, that is an invalid function call, you need to include the brackets, ie center();. You may have to create an event listener for the window resize too. Commented Apr 10, 2013 at 1:16

3 Answers 3

1

you have to add px, Element.style.marginLeft do not accept numbers. It should be valid CSS property (margin-left) value; It can be 10px or 5% or auto;

document.getElementById("center_div").style.marginLeft = x + 'px';
Sign up to request clarification or add additional context in comments.

Comments

1

Your code is fine, but missing one thing. You have to put "px" after the X variable. In other word, it should be: document.getElementById("center_div").style.marginLeft = x+"px"; Otherwise, the browser will not know its unit.

I made a sample in jsfiddle, this would be a working example. Try it. http://jsfiddle.net/TLPak/

PS. I've updated the code to include the window.onresize in it. (And some improvement, the DIV's width considered.) http://jsfiddle.net/TLPak/1/ Trigger it by click event or on window resize event are both OK. Hope it has some help to you.

function center() {
    var x=window.innerWidth;    
    x = x/2;

    var y = document.getElementById("center_div").offsetWidth;
    y = y/2;

    document.getElementById("center_div").style.marginLeft = x - y + "px"; 
}

window.onresize = center;

2 Comments

This doesn't center the object, it puts the top left corner of the object into the center. You need to update the margin left
OK, I revised the code. It will work on window resize event now.
0

I think what you're looking for is the css property margin: auto . Random example (not mine): http://bluerobot.com/web/css/center1.html . Additonally, you'll want width: 50% . Is that what you're looking for? Let me know, and I'll change my answer if need be. :)

1 Comment

He wants to use javascript

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.