Image 在响应流体设计中,垂直对齐div中高度较低的图像标签
我在这里阅读了一些关于居中元素的文章和解决方案,同时我正在尝试将图像垂直居中到一个高度小于图像的div 我过去依赖于背景图像,但现在我正在寻找一种解决方案,使用高度未知的图像标签,它可以安全地与响应设计一起使用,并垂直对齐图像,以便比div更大的部分位于外部(顶部和底部) 这是我的密码: HTML:Image 在响应流体设计中,垂直对齐div中高度较低的图像标签,image,css,responsive-design,vertical-alignment,Image,Css,Responsive Design,Vertical Alignment,我在这里阅读了一些关于居中元素的文章和解决方案,同时我正在尝试将图像垂直居中到一个高度小于图像的div 我过去依赖于背景图像,但现在我正在寻找一种解决方案,使用高度未知的图像标签,它可以安全地与响应设计一起使用,并垂直对齐图像,以便比div更大的部分位于外部(顶部和底部) 这是我的密码: HTML: .img-container { height:260px; position:relative; text-align: center; overflow: hidden;
.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;
}
(工作正常,但不确定为什么与某些浏览器存在一些差异)
下面是一个屏幕截图,说明我需要如何处理我的图像:
更新:
我添加了这段jQuery,并在CSS中进行了一些更新
所以我的问题是:有没有一种不用jQuery只使用CSS就能做到这一点的方法
$(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;
}
呵呵,几个月前我做过这个,我可以告诉你很多不可行的事情。。。最后,我使用了javascript和相对定位…尝试将其设置为背景图像,并使用
背景大小:cover代码>谢谢两位,@philwills:我已经更改了定位用法,但使用了一个jQuery,这是为了避免使用。@Zachsauier Saucier:是的,我曾经使用背景解决方案,但出于某些原因和打印兼容性需要一个图像标记:)@hsobhy背景图像应该可以打印。。。
$(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;
}