Search code examples
javascripthtmlalignmentimage

How to align an image to the center using Javascript?


Forgive me, I am still new to Javascript/HTML/PHP. In my HTML code, I have a reference to a JavaScript function in a file DisplayImage.js:

<body>
<div id="display_image" align="center">
    <script type="text/javascript" src="DisplayImage.js"></script>
</div>
</body>

Where a section of the DisplayImage.js JavaScript code is:

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;
    document.body.appendChild(img);
}   

show_image("sample1.jpg", 900, 690, "sample image #1");

This JS function just displays whatever image I want to pass into it onto my page. My problem is, it is always left-aligned. I would like the image to be aligned in the center. I tried putting align="center" into the div tag in my HTML code but that doesn't work, so I am assuming you need to do this from the JS function.

Can anyone help me make the image center-aligned here?


Solution

  • As the others have mentioned, use "margin: 0 auto;" on the img tag. However, the image needs to be set to "display: block;"

    #display_image > img {
        display: block;
        margin: 0 auto;
    }
    

    http://jsfiddle.net/slamborne/yffwN/