Why doesn't margin:auto center an image?

HtmlCss

Html Problem Overview


<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?

Html Solutions


Solution 1 - Html

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.

Solution 2 - Html

You need to render it as block level;

img {
   display: block;
   width: auto;
   margin: auto;
}

Solution 3 - Html

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>

Solution 4 - Html

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.

Solution 5 - Html

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.

Solution 6 - Html

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

Solution 7 - Html

open div then put

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

image tag (or) content

close div

Solution 8 - Html

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoe PhillipsView Question on Stackoverflow
Solution 1 - HtmlKeltexView Answer on Stackoverflow
Solution 2 - HtmlTheDeadMedicView Answer on Stackoverflow
Solution 3 - HtmlPranay RanaView Answer on Stackoverflow
Solution 4 - HtmlRyan HollingsworthView Answer on Stackoverflow
Solution 5 - HtmlCatwomanView Answer on Stackoverflow
Solution 6 - HtmlSalilView Answer on Stackoverflow
Solution 7 - HtmlHamd IslamView Answer on Stackoverflow
Solution 8 - HtmlDinoView Answer on Stackoverflow