CSS Margin: 0 Auto; doesn't work on <img> tag

My markup is simple and I am using inline CSS. My goal is to get the centering of the image using an margin: 0 auto;

in style

HTML attribute . Here is the code I tried:

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

Run codeHide result


Why isn't the CSS centering mine <img>

?

+3


source to share


4 answers


You must use display: block

to make an margin: 0px auto

effect.



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

Run codeHide result


+20


source


The style attribute syntax is incorrect in a div. Also, change the style on the img tag like this:



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

      

+2


source


Img

is inline, so width: 0 auto

won't work if you don't install display: block

. Or you can focus it on text-align: center

, which is a little weird but should work in a similar way.

Also, you should consider discontinuing using inline styles. This 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, also margin-left:0 auto; margin-right:0 auto;

not really. The correct form would be either

margin: 0 auto;

      

or

margin-left: auto;
margin-right: auto;

      

+1


source


text-align: center;

      

In image tags, it seems like w3c doesn't care.

display: block;
margin: 0 auto;

      

Must be!

Given this post

0


source







All Articles