Html 为什么不让边距:自动居中图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3015223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:24:54  来源:igfitidea点击:

Why doesn't margin:auto center an image?

htmlcss

提问by Joe Phillips

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

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

div100%扩展,因为它应该,但图像没有中心本身。为什么?

回答by Keltex

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

因为您的图像是内联块元素。您可以将其更改为块级元素,如下所示:

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

and it will be centered.

它将居中。

回答by TheDeadMedic

You need to render it as block level;

您需要将其渲染为块级;

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

回答by Pranay Rana

Add style="text-align:center;"

添加 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>

回答by Ryan Hollingsworth

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.

我的图像从父类继承了一个 float:left 。通过设置 float:none 我能够使 margin:0 auto 和 display: block 正常工作。希望它可以在未来帮助某人。

回答by Catwoman

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.

我发现我必须为对象定义一个特定的宽度,否则其他任何东西都不会使其居中。相对宽度不起作用。

回答by Dino

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.

我发现... margin: 0 auto; 为我工作。但我也看到它不起作用,因为该类被另一个具有 ... float:left; 的特殊性所压倒。所以请注意您可能需要添加 ... float:none; 这在我的情况下有效,因为我正在编写媒体查询。

回答by Salil

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

回答by Hamd Islam

open divthen put

打开div然后放

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

imagetag (or) content

image标记(或)内容

close div

关闭div