The code below adjusts the margin of an img, so it’s centered in an div with width of 600px. It works in general, but sometimes it doesn’t and a second call is required.
Edit: Forgot to mention: This function is triggered by another, who is setting the source of the image to another, therefore changing the image.
Any help?
function adjustMargin(imageId) {
var image = document.getElementById(imageId);
image.setAttribute("style", "margin: 0 " + (300 - image.clientWidth / 2).toString() + "px");
}
The not-so-well working example can be seen here.
use css:
The img tag is an inline element and as
margin: 0 autowill only work on block elements you have to includedisplay: blockon the img css.An alternative to center inline elements is:
Demo of both methods here