动态裁剪图像CSS JavaScript/jQuery



我正在寻找一种在固定高度的div内动态垂直居中图像的方法。 我无法使图像成为背景图像。 我将拥有从 300x375 到 300x240 的各种高度图像。 我的内部div高度将是240,如果图像高于240,我想将图像居中。 因此,对于高度为 375 的一个,它将裁剪顶部和底部 76.5px。 如果高度为 300,它将裁剪 30px 的顶部和底部。

我已经尝试了多种方法,但似乎当我让较大的图像裁剪正确时,较小的图像会搞砸。

我将尝试建立一个jsfiddle,但想发布它,因为我猜这相当简单,即使我无法找到解决方案。

你不一定需要使用 js,尝试使用 flexbox。

.HTML

<div id="root">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Circle_-_black_simple.svg/1024px-Circle_-_black_simple.svg.png">
</div>

.CSS

#root {
width: 300px;
height: 240px;
overflow: hidden;
display: flex;
flex-direction: column;
justify-content: center;
}
#root > img {
width: 300px;
height: 375px;
}

https://codepen.io/jc3m-the-flexboxer/pen/deEvpM

假设 HTML 布局

<div class="one">
<img src="https://placeimg.com/300/375/any">
</div>
<div class="one">
<img src="https://placeimg.com/300/240/any">
</div>

您可以循环访问div,并将图像顶部的边距设置为负值,即 240 与图像高度之差的一半

$(document).ready(function() {
$('.one img').each( function() {
if( $(this).height() > 240 ) {
var diff = ($(this).height() - 240) /2
$(this).css('margin-top', (diff * -1) + 'px')
}
})
})

div 需要设置为隐藏溢出才能正常工作。

小提琴:https://jsfiddle.net/calder12/29s5gnLq/

最新更新