How to align an image from Javascript?

1

Good morning, I'm trying to align (center) an image, but I can not get it.
What am I doing wrong?

var imagen =document.createElement("img");

imagen.src="ejemplo.jpg";
imagen.width="500";
imagen.height="300";
imagen.align="middle";


document.body.appendChild(imagen);
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
 
    <title>Document</title>
</head>
<body>
    
    <script src="Ejemplo1_ext.js"></script>
</body>
</html>
       
asked by Ale 25.11.2017 в 20:45
source

3 answers

1

I have solved it in the following way:

Adding styles img :

display: block; and margin: auto;

With this you focus:

var imagen = document.createElement("img");
imagen.src="ejemplo.jpg";
imagen.width="500";
imagen.height="300";

imagen.style.display="block";
imagen.style.margin = "auto";

document.body.appendChild(imagen);
    
answered by 25.11.2017 / 20:57
source
1

You need to enter the image inside a div and align the content of the same center:

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">

    <title>Document</title>
</head>
<body>
    <div id="div_container" />
    <script> 
    var imagen =document.createElement("img");
    var div_contenedor = document.getElementById('div_container')

div_contenedor.width="100%";
div_contenedor.display="flex";
div_contenedor.align="center";
imagen.src="ejemplo.jpg";
imagen.width="500";
imagen.height="300";

div_contenedor.appendChild(imagen);
</script>
</body>
</html>
    
answered by 25.11.2017 в 21:23
-2

Write   <center> here you put the command of the image and you close the center   </center> automatically centers it.

    
answered by 25.11.2017 в 21:00