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

img {
    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;
}

其他回答

如果你想将图像设置为背景,我有一个解决方案:

.image {
    background-image: url(yourimage.jpg);
    background-position: center;
}

将非背景图像居中取决于您想要将图像显示为内联(默认行为)还是块元素。

内联情况

如果你想保持图像的CSS属性的默认行为,你需要将你的图像包装在另一个块元素中,你必须设置text-align: center;

块格

如果你想把图像看作一个单独的块元素,那么text-align属性没有意义,你应该这样做:

IMG.display {
    display: block;
    margin-left: auto;
    margin-right: auto;
}

你问题的答案是:

属性text-align: center;将图像居中的好方法 使用CSS呢?

是也不是。

是的,如果图像是其包装器中的唯一元素。 不,如果你在图像的包装器中有其他元素,因为所有的子元素都是图像的兄弟姐妹,将继承text-align属性:并且可能你不喜欢这个副作用。

参考文献

内联元素列表 定心的事情

有时我们直接在WordPress管理员的页面中添加内容和图像。当我们将图像插入到内容中并想要对齐该中心时。代码显示为:

 **<p><img src="https://abcxyz.com/demo/wp-content/uploads/2018/04/1.jpg" alt=""></p>**

在这种情况下,你可以像这样添加CSS内容:

article p img{
    margin: 0 auto;
    display: block;
    text-align: center;
    float: none;
}

我找到的最简单的解决方案是添加到我的img-element:

style="display:block;margin:auto;"

看来我不需要像别人建议的那样在auto前面加0。也许这是正确的方法,但对于我的目的来说,没有“0”也足够了。至少在最新的Firefox、Chrome和Edge上是这样。

如果你的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;
}