Why doesn't margin:auto center an image?

<html>
<head>
<title>Test</title>
</head>
<body>
<div>
<img src="queuedError.jpg" style="margin:auto; width:200px;" />
</div>
</body>
</html>

The div expands to 100% as it should but the image does not center itself. Why?

122563 次浏览

Because your image is an inline-block element. You could change it to a block-level element like this:

<img src="queuedError.jpg" style="margin:auto; width:200px;display:block" />

and it will be centered.

Add style="text-align:center;"

try below code

<html>
<head>
<title>Test</title>
</head>
<body>
<div style="text-align:center;vertical-align:middle;">
<img src="queuedError.jpg" style="margin:auto; width:200px;" />
</div>
</body>
</html>

You need to render it as block level;

img {
display: block;
width: auto;
margin: auto;
}
<div style="text-align:center;">
<img src="queuedError.jpg" style="margin:auto; width:200px;" />
</div>

open div then put

style="width:100% ; margin:0px auto;"

image tag (or) content

close div

i know this is an old post, but wanted to share how i solved the same problem.

My image was inheriting a float:left from a parent class. By setting float:none I was able to make margin:0 auto and display: block work properly. Hope it may help someone in the future.

I've found that I must define a specific width for the object or nothing else will make it center. A relative width doesn't work.

I have found... margin: 0 auto; works for me. But I have also seen it NOT work due to the class being trumped by another specificity that had ... float:left; so watch for that you may need to add ... float:none; this worked in my case as I was coding a media query.