我有一个 div,大小为 145px X 145px。我在这个 div 里面放了一张图片,图片的大小可以是任何尺寸(最长的一边是 130px)。我希望图片垂直居中于 div 中。我试过的所有方法都能在大多数浏览器中正常工作,但在 IE7 中无法正常工作。我需要一种在 IE7 中也能正常工作的方法。
我有一个 div,大小为 145px X 145px。我在这个 div 里面放了一张图片,图片的大小可以是任何尺寸(最长的一边是 130px)。我希望图片垂直居中于 div 中。我试过的所有方法都能在大多数浏览器中正常工作,但在 IE7 中无法正常工作。我需要一种在 IE7 中也能正常工作的方法。
这是一个跨浏览器的解决方案:
<div class="img-container"><img src="picture.png" class="cropped"/></div>
div.img-container {
width: 390px;
height: 211px;
position: relative;
margin-left: auto;
margin-right: auto;
overflow: hidden;
}
img.cropped {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
<div style="background:url(myimage.jpg) no-repeat center center"></div>
我不确定IE7是否适用,但对于IE9和其他现代浏览器,以下内容是有效的。
.picturecontainer{
width:800px;
height:800px;
border:solid 1px;
display:table-cell;
vertical-align:middle;
}
.horizontalcenter{
display:block;
margin-left:auto;
margin-right:auto;
vertical-align:middle;
}
使用它
<div class="picturecontainer"><img src="" class="horizontalcenter"/></div>
不确定你已经尝试了什么,但是如果图片被显示为内联元素,则 vertical-align CSS 属性应该有效。
有关 vertical-align 的一些信息:http://www.w3schools.com/css/pr_pos_vertical-align.asp
如果你必须考虑所有图像的高度,那么这几乎是唯一的方法,而无需使用 JavaScript。
如果图像不是内联元素,并且您只需要适应具有一致高度的图像,则可以执行以下操作:
img {
margin-top: -50px; /* This number should be half the height of your image */
position: absolute;
top: 50%;
}
对我来说,使用 line-height
属性解决了这个问题。
参考资料:在 div 中垂直对齐图像
HTML:
<div class="img_thumb">
<a class="images_class" href="large.jpg" rel="images"><img src="http://www.minfo.pt/fotos/_cache/produtos/0/068.M.976010002__thumbnail_50_50_true_sharpen_1_1.JPG" title="img_title" alt="img_alt" /></a>
</div>
CSS:
.img_thumb {
float: left;
height: 120px;
margin-bottom: 5px;
margin-left: 9px;
position: relative;
width: 147px;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 3px;
line-height:120px;
text-align:center;
}
.img_thumb img {
vertical-align: middle;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
imagepos = function () {
$('img').each(function () {
imgheight = Math.round($(this).height() / 2);
imgwidth = Math.round($(this).width() / 2);
$(this).attr("style", "margin-top: -" + imgheight + "px; margin-left: -" + imgwidth + "px; opacity:1;");
});
}
$(window).load(imagepos);
</script>
你还需要一点点的CSS:
div
{
position:relative;
}
img
{
display:block;
margin:auto;
max-width:100%;
position:absolute;
top:50%;
left:50%;
opacity:0;
}