开发者

Why doesn't margin:auto center an image?

<html>
<head>
<title>Test</title>
</head>
<body>
    <div>
        <img src="queuedError.jpg" style="margin:auto; width:200px;" /开发者_运维问答>
    </div>
</body>
</html>

The div expands to 100% as it should but the image does not center itself. Why?


Because your image is an inline-block element. You could change it to a block-level element like this:

<img src="queuedError.jpg" style="margin:auto; width:200px;display:block" />

and it will be centered.


You need to render it as block level;

img {
   display: block;
   width: auto;
   margin: auto;
}


Add style="text-align:center;"

try below code

<html>
<head>
<title>Test</title>
</head>
<body>
    <div style="text-align:center;vertical-align:middle;">
        <img src="queuedError.jpg" style="margin:auto; width:200px;" />
    </div>
</body>
</html>


i know this is an old post, but wanted to share how i solved the same problem.

My image was inheriting a float:left from a parent class. By setting float:none I was able to make margin:0 auto and display: block work properly. Hope it may help someone in the future.


I've found that I must define a specific width for the object or nothing else will make it center. A relative width doesn't work.


open div then put

style="width:100% ; margin:0px auto;" 

image tag (or) content

close div


<div style="text-align:center;">
    <img src="queuedError.jpg" style="margin:auto; width:200px;" />
</div>


I have found... margin: 0 auto; works for me. But I have also seen it NOT work due to the class being trumped by another specificity that had ... float:left; so watch for that you may need to add ... float:none; this worked in my case as I was coding a media query.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜