Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't margin:auto center an image?

Tags:

html

css

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

like image 822
Joe Phillips Avatar asked Jun 10 '10 14:06

Joe Phillips


People also ask

Why does margin auto not center?

Important: The reason your margin: auto; is not centering is because you haven't set a fixed width to the element you're trying to center. We also specify text-align: center; as this will center the text inside the inner container.

Does margin auto work on images?

Another way to center an image is by using the margin: auto property (for left-margin and right-margin). However, using margin: auto alone will not work for images.

How do you center an image on margin?

To center an image, we have to set the value of margin-left and margin-right to auto and make it a block element by using the display: block; property. If the image is in the div element, then we can use the text-align: center; property for aligning the image to center in the div.

How do you use margin auto to center?

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.


2 Answers

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.

like image 178
Keltex Avatar answered Oct 06 '22 13:10

Keltex


You need to render it as block level;

img {    display: block;    width: auto;    margin: auto; } 
like image 29
TheDeadMedic Avatar answered Oct 06 '22 14:10

TheDeadMedic