简体   繁体   中英

CSS Margin: 0 Auto; is not working on <img> tag

My markup is simple, and I'm using inline CSS. My goal is to get the image centered using margin: 0 auto; in the style HTML attribute. Here's code that I have tried:

 <div style="width: 100%;"> <img src="http://dummyimage.com/200x300/000000/fff" style="margin: 0 auto;"/> </div> 

Why is the CSS not centering my <img> ?

You must use display: block to make margin: 0px auto have any effect.

 <div style="width: 100%;"> <img src="http://placekitten.com/g/200/300" style="display: block; margin: 0px auto;"> </div> 

Your style attribute syntax is wrong on the div. Also, change the style on the img tag like so:

<div style="width:100%">
<img src="https://4c206b86fe5a0219d31bb1ae55c8bbdc3f028879-www.googledrive.com/host/0BzEiAml5ygAeU3N6QTRUUW53Vjg/" width="50%" height="auto" style="margin:0 auto; display:block">
</div>

Img is an inline element, so width: 0 auto won't work, unless you set display: block . Or you can center it with text-align: center , which is a bit weird, but should work similarly.

Also, you should consider stop using inline styles. It makes html markup harder to read, harder to maintain etc. Styles belong to separate css files and you should try to avoid inline styles whenever possible. (and html attributes like width, height etc AS WELL!)

Well, and also margin-left:0 auto; margin-right:0 auto; margin-left:0 auto; margin-right:0 auto; isn't really valid. The correct form would be either

margin: 0 auto;

or

margin-left: auto;
margin-right: auto;
text-align: center;

On image tags seems not to be w3c valid anyway.

display: block;
margin: 0 auto;

Should be!

Considering this post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM