使用CSS垂直和水平居中图像 [英] Center an Image vertically and horizontally using CSS
问题描述
当我不知道图片的大小时,如何垂直和水平居中图片?我问此问题,有人建议使用表。这不是我第一次听到一个表可以做,但我试过没有运气。
How do I vertically and horizontally center an image when I do not know the size of it? I asked this question and someone suggested using a table. This isn't the first time I heard a table can do it but I tried without luck.
搜索只有当我知道图像的大小才得到我的结果。如何用表来做这个?
Searching SO only got me results when I do know the size of the image. How do I do this with a table?
注意:JavaScript / jQuery不是首选,但如果有一个解决方案,我会对它开放。
NOTE: JavaScript/jQuery is not preferred but if there's a solution with it I'm open to it.
推荐答案
使用表格:
<table height="400">
<tbody>
<tr>
<td valign="middle"><img /></td>
</tr>
</tbody>
</table>
400是我选择的。你需要在表格上定义一个高度,因此它比你的图像高。
The 400 is just something I picked. You will need to define a height on table so it is taller than your image.
如果你想尝试和使用div和垃圾,但是如果你不在乎你不在乎,jquery解决方案将是很好的。你还必须依赖于JS被打开。
A jquery solution would be good if you wanted to try and use divs and junk, but if you don't care you don't care. You also have to rely on JS being turned on.
HTML:
<div id="imgContainer" style="position:relative;">
<img style="position:absolute;" />
</div>
JS:
$('#imgContainer > img').each(function(){
//get img dimensions
var h = $(this).height();
var w = $(this).width();
//get div dimensions
var div_h =$('#imgContainer').height();
var div_w =$('#imgContainer').width();
//set img position
this.style.top = Math.round((div_h - h) / 2) + 'px';
this.style.left = '50%';
this.style.marginLeft = Math.round(w/2) + 'px';
});
这篇关于使用CSS垂直和水平居中图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!