问题
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;"/>
回答1:
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
.
回答2:
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.
回答3:
You can center auto width div using display:table;
div{
margin: 0px auto;
float: none;
display: table;
}
回答4:
In my case the problem was that I had set min and max width without width itself.
回答5:
Whenever we don't add width and add margin:auto
, I guess it will not work. It's from my experience. Width gives the idea where exactly it needs to provide equal margins.
回答6:
there is a alternative to margin-left:auto; margin-right: auto;
or margin:0 auto;
for the ones that use position:absolute;
this is how:
you set the left position of the element to 50% (left:50%;
) but that will not center it correctly in order for the element to be centered correctly you need to give it a margin of minus half of it`s width, that will center your element perfectly
here is an example: http://jsfiddle.net/35ERq/3/
回答7:
For a bootstrap button:
display: table;
margin: 0 auto;
回答8:
put this in the body's css: background:#3D668F; then add: display: block; margin: auto; to the img's css.
来源:https://stackoverflow.com/questions/5734199/auto-margins-dont-center-image-in-page