简体   繁体   中英

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?

Adding the line img.style.margin = "0 auto"; should do the trick.

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/

You can modify your div with a CSS style tag.

<div id="display_image" style="display:block; margin:0 auto;">
    <script type="text/javascript" src="DisplayImage.js"></script>
</div>

If you're modifying more than one instance of this, change your CSS (embedded or external file)

<!DOCTYPE html>
<head>
 <style>
    img.center {
        position: absolute;
        top: 50%;
        bottom: 50%;
        left: 50%;
        right: 50%;
        margin: auto;
    }
</style>

<script>

function ex() {
  var x = document.createElement("IMG")
  x.setAttribute("class", "center")
  x.setAttribute("src", "example.png");
  x.setAttribute("width", "50");
  x.setAttribute("height", "50");
  x.setAttribute("alt", "example");
  document.body.appendChild(x);
}

</script>
</head>
<body>
<button onclick="ex()">click</button>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM