在div水平中心图像

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

谢谢你的帮助!

484194 次浏览

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

我认为最好是做文本对齐中心div和让图像照顾高度。只需要为div指定一个顶部和底部的填充,以便在image和div之间有空格

<div class="outer">
<div class="inner">
<img src="http://1.bp.blogspot.com/_74so2YIdYpM/TEd09Hqrm6I/AAAAAAAAApY/rwGCm5_Tawg/s320/tall+copy.jpg" alt="tall image" />
</div>
</div>
<hr />
<div class="outer">
<div class="inner">
<img src="http://www.5150studios.com.au/wp-content/uploads/2012/04/wide.jpg" alt="wide image" />
</div>
</div>

CSS

img
{
max-width: 100%;
max-height: 100%;
display: block;
margin: auto auto;
}


.outer
{
border: 1px solid #888;
width: 100px;
height: 100px;
}


.inner
{
display:table-cell;
height: 100px;
width: 100px;
vertical-align: middle;
}

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

.top_image img { margin:0 auto; }

更多信息和例子来自W3C。

同样,在解决方案中植入维度是痛苦的。

简单地设置:

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

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

这是所有。

注意,你还必须为外层的div设置初始min-width

我希望这对你有所帮助:

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

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

例:

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

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

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

GG美国