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

img {
    text-align: center;
}

当前回答

你可以在父元素上使用text-align: center,并将img更改为display: inline-block→,因此它的行为就像一个文本元素,如果父元素有宽度,它将居中!

img {
    display: inline-block
}

其他回答

简单地改变父对齐:)

在父属性上试试这个:

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

边框为0的Display: block和text-align: center元素都不适合我。

这是我的解决方案:

img.center {
    position: absolute;
    transform: translateX(-50%);
    left: 50%;
}

大多数浏览器都支持translateX

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

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

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

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

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

我建议有三种方法来居中一个元素:

Using the text-align property .parent { text-align: center; } <div class="parent"> <img src="https://placehold.it/60/60" /> </div> Using the margin property img { display: block; margin: 0 auto; } <img src="https://placehold.it/60/60" /> Using the position property img { display: block; position: relative; left: -50%; } .parent { position: absolute; left: 50%; } <div class="parent"> <img src="https://placehold.it/60/60" /> </div>


第一种和第二种方法只在父元素至少和图像一样宽的情况下才有效。当图像比其父图像宽时,图像将不会保持居中!!

但是: 第三种方法是一个很好的方法!

这里有一个例子:

img { 显示:块; 位置:相对; 左:-50%; } .parent { 位置:绝对的; 左:50%; } < div class = "父" > <img src="http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/img_01.jpg" /> < / div >