[英]Make image fill div proportionally and center image vertically
如果以前有人使用过InDesign,则当您将图像放置在框架中时,右键单击框架将允许您选择“ 按比例填充”选项,以便整个框架都包含图像,并且所有溢出都被隐藏,然后,您便可以可以使内容居中 。
如何在浏览器中实现这种效果?
我创建了一个小提琴 ,可以帮助实现这一结果。
但是,如果div.frame
宽度大于其图像宽度,这将导致图像扩展到大于其分辨率。
假设以下HTML
<div class="frame">
<img src="http://stuffpoint.com/parrots/image/240658-parrots-white-parrot.jpg" />
</div>
这将应用以下样式
.frame {
width: 100%;
height: 200px;
overflow: hidden;
position: relative;
}
.frame img {
width: 100%;
}
强制jQuery在加载和调整大小时将图像垂直居中
$(function(){
centerImageVertically();
$(window).resize(function() {
centerImageVertically();
});
function centerImageVertically() {
var imgframes = $('.frame img');
imgframes.each(function(i){
var imgVRelativeOffset = ($(this).height() - $(this).parent().height()) / 2;
$(this).css({
'position': 'absolute',
'top': imgVRelativeOffset * -1
});
});
}
});
更新:以上构建JavaScript的另一种方式:
$(function () {
var centerImageVertically = function () {
var imgframes = $('.frame img');
imgframes.each(function (i) {
var imgVRelativeOffset = ($(this).height() - $(this).parent().height()) / 2;
$(this).css({
'position': 'absolute',
'top': imgVRelativeOffset * -1
});
});
};
centerImageVertically();
$(window).resize(centerImageVertically);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.