我在一个div (class="top_image")中有一个img,我想要这个图像正好在div的中间,但我没有尝试工作…

谢谢你的帮助!


当前回答

Text-align: center只适用于水平居中。为了使它处于完整的中心,垂直和水平,您可以执行以下操作:

div
{
    position: relative;
}
div img
{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: [-50% of your image's width];
    margin-top: [-50% of your image's height];
}

其他回答

这里发布的每个解决方案都假设您知道img的维度,这不是一个常见的场景。此外,在解决方案中植入维度是很痛苦的。

简单地设置:

/* for the img inside your div */
display: block;
margin-left: auto;
margin-right: auto;

or

/* for the img inside your div */
display: block;
margin: 0 auto;

这是所有。

注意,您还必须为外部div设置初始最小宽度。

Text-align: center只适用于水平居中。为了使它处于完整的中心,垂直和水平,您可以执行以下操作:

div
{
    position: relative;
}
div img
{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: [-50% of your image's width];
    margin-top: [-50% of your image's height];
}

我花了太长时间才想明白。真不敢相信居然没人提到中心标签。

Ex:

<center><img src = "yourimage.png"/></center>

如果你想要将图像大小调整为百分比:

<center><img src = "yourimage.png" width = "75%"/></center>

GG美国

我希望这对你有所帮助:

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

W3C提供了一个非常简单而优雅的解决方案。简单地使用margin:0自动声明如下:

.top_image img { margin:0 auto; }

来自W3C的更多信息和示例。