无需拉伸即可完全填充图像

Len*_*art 23 html javascript css image

我有各种尺寸的大图像,需要在两个维度上完全填充240px的300px容器.这是我现在得到的,只适用于一个方面:

http://jsfiddle.net/HsE6H/

HTML

<div class="container">
    <img src="http://placehold.it/300x1500">
</div>
<div class="container">
    <img src="http://placehold.it/1500x300">
</div
Run Code Online (Sandbox Code Playgroud)

CSS

.container {
height: 300px;
width: 240px;
background-color: red;
float: left;
overflow: hidden;
margin: 20px;
}

img {
max-width: 100%;
height: auto;
}
Run Code Online (Sandbox Code Playgroud)

比例应该保持不变.基本上,应该在宽度上切除宽图像,而在高度上需要切断高图像.因此,只需放大填充容器所需的数量即可.

不知道为什么我不能让它工作,我需要JavaScript吗?

编辑:要清楚.在小提琴上我需要一切红色.进来的图像是动态的,因此我无法使用背景图像.我愿意使用JavaScript.谢谢!:)

Mar*_*det 42

自动调整图像以适应Div - 使CSS工作

这是一种方法,从以下HTML开始:

<div class="container portrait">
    <h4>Portrait Style</h4>
    <img src="http://placekitten.com/150/300">
</div>
Run Code Online (Sandbox Code Playgroud)

和CSS:

.container {
    height: 300px;
    width: 240px;
    background-color: red;
    float: left;
    overflow: hidden;
    margin: 20px;
}
.container img {
    display: block;
}

.portrait img {
    width: 100%;
}
.landscape img {
    height: 100%;
}
Run Code Online (Sandbox Code Playgroud)

和演示小提琴:http://jsfiddle.net/audetwebdesign/QEpJH/

如果将图像定向为纵向,则需要将宽度缩放为100%.相反,当图像是横向时,您需要缩放高度.

不幸的是,CSS中没有针对图像纵横比的选择器组合,因此您无法使用CSS来选择正确的缩放比例.

此外,由于图像的左上角固定在包含块的左上角,因此没有简单的方法使图像居中.

jQuery Helper

您可以使用以下jQuery操作来确定基于图像的宽高比设置的类.

$(".container").each(function(){
    // Uncomment the following if you need to make this dynamic
    //var refH = $(this).height();
    //var refW = $(this).width();
    //var refRatio = refW/refH;

    // Hard coded value...
    var refRatio = 240/300;

    var imgH = $(this).children("img").height();
    var imgW = $(this).children("img").width();

    if ( (imgW/imgH) < refRatio ) { 
        $(this).addClass("portrait");
    } else {
        $(this).addClass("landscape");
    }
})
Run Code Online (Sandbox Code Playgroud)

对于每个图像.container,获取高度和宽度,测试是否width<height然后设置适当的类.

另外,我添加了一个检查以考虑包含块的宽高比.之前,我暗中假设了一个方形视图面板.


Bur*_*hts 5

对于任何想要执行此操作但没有动态图像的人,这里有一个使用背景图像的全CSS解决方案。

<div class="container" 
    style="background-image: url('http://placehold.it/300x1500'); 
    background-size: cover; background-position: center;">
</div>
<div class="container" 
    style="background-image: url('http://placehold.it/1500x300'); 
    background-size: cover; background-position: center;">
</div>
Run Code Online (Sandbox Code Playgroud)

使用“背景大小:封面”可以使图像缩放以覆盖所有div,同时保持宽高比。CSS也可以移动到CSS文件中。尽管是动态生成的,但是background-image属性必须保留在style属性中。