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?
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?
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;
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. :)