Pergunta

I'm coding my graduate work and I'm having trouble centering div with contents that change change (image upload).

In my script I create <img id="uploaded"> and insert the uploaded image into it, and this <img> is inserted in <div id="canvas"></div>.

In my CSS :

#canvas {
    position: absolute;
    left: 50%;
    z-index: 500;
}

I tried :

var canvaswidth = document.getElementById('uploaded').width;

for getting the img width, and I want to add a negative left margin for centering my div.

I tried :

document.getElementById('canvas').style.marginLeft = - canvaswidth / 2;

But that doesn't work. Can you help me make it work?

Foi útil?

Solução

You need units:

document.getElementById('canvas').style.marginLeft = - canvaswidth /2 + 'px';

However, you could use "absolute centering":

#canvas {
    position: absolute;
    left: 0;
    right: 0;
    margin: auto;
}

And just set the width to the desired value:

document.getElementById('canvas').style.width = canvaswidth + 'px';
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top