CSS / Javascript图像大小适合裁剪和保留纵横比

时间:2014-02-16 20:23:33

标签: javascript html css image

我有一个大小为180x270的块,我需要显示图像

图像尺寸可能会有所不同,我想确保它可以扩展或缩小,以便较小的边框(高度或宽度)与块匹配,而较大的边框会在保留纵横比的同时被裁剪。

示例如下: - 360x600的图像大小调整为180x300,我将高度从300减少到270 - 100x135的图像调整为200x270,我将宽度从200剪裁到180

基本上我想确保在展开/缩小图像时没有空白区域,同时通过裁剪超出块的部分来保留纵横比

有关可以处理此问题的css或javascripts的任何建议吗?

2 个答案:

答案 0 :(得分:3)

好像您正在寻找background-size:cover,当图片为background-image

background:url(imgurl.jpg) /* Other background image properties */;
background-size:cover;

Demo

答案 1 :(得分:2)

Zach的解决方案最好是你可以使用bg-image来完成任务,但是如果你需要使用<img>标签(有时这是advised),那么你需要javascript计算图像的纵横比,并确定它是否比目标框架更蹲或更垂直拉伸。然后还有一点CSS:

<强>的JavaScript

//obtain a dom-reference for the image using getElementById
//or by some other means depending on what you know of its HTML
var img = document.getElementById('some-image-id') 


var aspectRatio = img.clientWidth/img.clientHeight;

//if the img is more squat, set it's height equal to the target frame's height
if(aspectRatio > (270/180)){
    img.style.height = 180 //image is
}
//otherwise the image is more vertically stretched
// so set the img width equal to the target frame's width
else{
    img.style.width = 270;
}

这将设置

<强> CSS

最后,无论装配方式如何,都要将包装纸内部的超大图像垂直和水平居中:

.wrapper{
    position:relative;
    display:inline-block; 
}
.wrapper img{
    position:absolute;
    top:-9999px;
    right:-9999px;
    bottom:-9999px;
    left:-9999px;
}
相关问题