<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?
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.
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.
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.
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.
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.
You need to render it as block level;
img { display: block; width: auto; margin: auto; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With