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?
-
1Please define what "doesn't work" means.Lee Taylor– Lee Taylor2013年04月10日 01:11:53 +00:00Commented Apr 10, 2013 at 1:11
-
What are you trying to do with your code? Can you explain it?eggy– eggy2013年04月10日 01:14:24 +00:00Commented 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.lukeocom– lukeocom2013年04月10日 01:16:39 +00:00Commented Apr 10, 2013 at 1:16
3 Answers 3
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';
Comments
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
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. :)