属性text-align: center;一个好方法来中心使用CSS图像?

img {
    text-align: center;
}

当前回答

使用网格来堆叠图像。这很简单,这是代码

.grid {
   display:grid;
}

.grid img {
    display:block;
    margin:0 auto;
}

其他回答

除非你需要支持旧版的ie浏览器。

现代的方法是在CSS中使用margin: 0 auto。

例如:http://jsfiddle.net/bKRMY/

HTML:

<p>Hello the following image is centered</p>
<p class="pic"><img src="https://twimg0-a.akamaihd.net/profile_images/440228301/StackoverflowLogo_reasonably_small.png"/></p>
<p>Did it work?</p>

CSS:

p.pic {
    width: 48px;
    margin: 0 auto;
}

这里唯一的问题是,段落的宽度必须与图像的宽度相同。如果你没有在段落上设置宽度,它将不起作用,因为它将假设100%并且你的图像将向左对齐,当然除非你使用text-align:center。

如果你喜欢,可以试试这把小提琴。

如果你的img元素在一个div中,它本身在另一个div中,它的显示被设置为flexbox,就像我这里的例子: (HTML)

<nav class="header">
            <div class="image">
                <img
                src=troll
                alt="trollface"
                ></img>
            </div>
            <div class="title">
                Meme Generator
            </div>
            <div class="subtitle">
                React Course - Project 3
            </div>
        </nav>

(CSS)

.header{
    display: flex;
}

.image{
    width: 5%;
    height: 100%;
}

.image > img{
    width: 100%;
}

你可以这样设置你的。image div垂直对齐:

.image{
    width: 5%;
    height: 100%;
    align-self: center;
}

在容器保存图像上,您可以使用css3 Flexbox来完美地将图像置于垂直和水平的中心。

让我们假设你有<div class="container">作为图像持有人:

然后作为CSS,你必须使用:

.container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

这将使这个div中的所有内容完全居中。

.img-container {
  display: flex;
}

img {
  margin: auto;
}

这将使图像在垂直和水平方向上处于中心位置

img{
    display: block;
    margin-right: auto;
    margin-left: auto;      
 }