我在这里阅读有关居中元素的文章和解决方案,而我正在尝试适合和垂直居中图像到高度低于图像的div。
我曾经依赖于背景图像,但现在我正在寻找一种解决方案来使用图像标签,其高度未知,可以安全地使用响应式设计并垂直对齐图像,以便div比div更大(顶部和底部)。
这是我的代码:
HTML:
(工作但不确定为什么与某些浏览器存在一些差异)
<div class="content">
<div class="img-container">
<div class="img-helper">
<img src="/media/projects/cats/large/cats_0001.jpg"></img>
</div>
</div>
</div>
CSS:
.img-container {
height:260px;
position:relative;
text-align: center;
overflow: hidden;
margin-bottom:20px;
}
.img-helper {
position: absolute;
top: -25%;
left: 0px;
display: block;
height:260px;
width:100%;
}
.img-helper img {
position: relative;
top:10px;
left: 0px;
width: 100%;
height: auto;
padding:0;
margin:0;
}
http://i.stack.imgur.com/WE1p5.png
更新
我已经添加了这段jQuery并且在CSS中进行了一些更新。
所以我的问题是:如果没有使用CSS的jQuery,有没有办法做到这一点?
$(document).ready(function () {
$('.img-helper>img').each(function () {
var imgHeight = $(this).outerHeight();
var divHeight = $(this).parent().innerHeight();
if (imgHeight > divHeight) {
$(this).css({ 'top' : "-" + ((imgHeight - divHeight )/2) + "px" });
}
else {
$(this).parent().css({ 'height' : imgHeight + "px" });
};
});
});
=============
CSS
=============
.img-container{
position:relative;
text-align: center;
overflow: hidden;
}
.img-helper {
position:relative;
display: block;
height:260px;
width:100%;
}
.img-helper img {
position:relative;
width: 100%;
height: auto;
padding:0;
}