开发者

Auto margins don't center image in page

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;"/>


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.


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.


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/


For a bootstrap button:

display: table; 
margin: 0 auto;


I remember someday that I spent a lot of time trying to center a div, using margin: 0 auto.

I had display: inline-block on it, when I removed it, the div centered correctly.

As Ross pointed out, it doesn't work on inline elements.


img{display: flex; max-width: 80%; margin: auto;}

This is working for me. You can also use display: table in this case. Moreover, if you don't want to stick to this approach you can use the following:

img{position: relative; left: 50%;}


put this in the body's css: background:#3D668F; then add: display: block; margin: auto; to the img's css.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜