我有一个在div中的img
( class="top_image"
),我想让这张图片正好居中于此div,但是我尝试过的方法都没有起作用...
感谢任何帮助!
这里发布的每个解决方案都假设您知道您的img
的尺寸,这并不常见。此外,将尺寸嵌入解决方案是困难的。
只需设置:
/* 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;
就这些。
需要注意的是,您还必须为外部
min-width
。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];
}
[-50%的图像宽度/高度]
:) - rgthree<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;
}
我认为最好将div设为文字居中,让图片控制高度。只需为div指定上下内边距即可在图片和div之间留出空间。可以看看这个例子:http://jsfiddle.net/Tv9mG/
.top_image img{
display: block;
margin: 0 auto;
}
例如:
<center><img src = "yourimage.png"/></center>
如果你想将图像按百分比调整大小:
<center><img src = "yourimage.png" width = "75%"/></center>
GG 美国