In this example the image is not centered. Why? My browser is Google Chrome v10 on windows 7, not IE.
<img src="/img/logo.png" style="margin:0px auto;"/>
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.
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.
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.
Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.
add display:block;
and it'll work. Images are inline by default
To clarify, the default width for a block
element is auto
, which of course fills the entire available width of the containing element.
By setting the margin to auto
, the browser assigns half the remaining space to margin-left
and the other half to margin-right
.
You can center auto width div using display:table;
div{
margin: 0px auto;
float: none;
display: table;
}
Under some circumstances (such as earlier versions of IE, Gecko, Webkit) and inheritance, elements with position:relative;
will prevent margin:0 auto;
from working, even if top
, right
, bottom
, and left
aren't set.
Setting the element to position:static;
(the default) may fix it under these circumstances. Generally, block level elements with a specified width will respect margin:0 auto;
using either relative
or static
positioning.
In my case the problem was that I had set min and max width without width itself.
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