2017-05-09 83 views
0

我试图用图像填充容器,但找不到解决方案。在容器div中的图像拟合

如果图片太短,我需要将它们设置为全高,但它们可能会溢出双方。 如果图像太窄,我需要将它们全宽,但它们可以溢出底部。

enter image description here

<div class="cb-img-fw four-image"> 
    <a href="postURL"><img src="imageURL"></a> 
</div> 

和CSS的

.four-grid-post > .four-image{ 
max-height: 184px; 
max-width: 271px; 
overflow: hidden; 
} 

.four-grid-post > .four-image img{ 
min-width: 100%; 
max-width: 100%; 
height: auto; 
} 

我也开到jQuery的解决方案,但我的内容加载与AJAX所以它可能会引起一些问题。

+0

的[我如何自动调整图像大小,以适应一个div容器(可能的复制http://stackoverflow.com/questions/3029422/how-do-i-auto -resize-an-image-to-fit-a-div-container) –

+0

@InnovaITveSolutions在该决定中,图形不会超出块的边界。 –

+0

我认为,它的重复[是否有一个等效于背景大小:封面和包含图像元素?](http://stackoverflow.com/questions/11670874/is-there-an-equivalent-to-background-大小覆盖和包含图像元素) – Tigran

回答

1

我建议在css background上更改img

.four-image { 
 
    display: block; 
 
    border: 1px solid gray; 
 
    width: 271px; 
 
    margin-bottom: 1em; 
 
} 
 

 
.four-image a { 
 
    display: block; 
 
    width: 271px; 
 
    height: 184px; 
 
    background-size: cover; 
 
    background-position: center center; 
 
}
<div class="cb-img-fw four-image"> 
 
    <a href="postURL" style="background-image: url('http://placehold.it/600x200');"></a> 
 
    600x200 
 
</div> 
 
<div class="cb-img-fw four-image"> 
 
    <a href="postURL" style="background-image: url('http://placehold.it/200x600');"></a> 
 
    200x600 
 
</div> 
 
<div class="cb-img-fw four-image"> 
 
    <a href="postURL" style="background-image: url('http://placehold.it/600x600');"></a> 
 
    600x600 
 
</div>

1

试试这个脚本 它将把你作为背景图片 图片,然后你可以给高度和宽度的背景图片,并使其背景大小盖

var images = $(".four-image").find("img"); 
$.each(images, function (index, item) { 
var $item = $(item), 
src = $item.attr('src'), 
cont = $item.closest('.four-image').css('background-image', 'url(' + src + 
')'); 
});  
+1

它是一个很好的解决方案。我用不同的地方谢谢:) –

2

你可以使用object-fitobject-position CSS3属性。 Edge尚未支持它们,但有a polyfill。 见feature support on CanIUse

.four-grid-post > .four-image { 
 
\t display: inline-block; 
 
\t height: 184px; 
 
\t width: 271px; 
 
\t overflow: hidden; 
 
\t border: dashed 2px red; 
 
} 
 

 
.four-grid-post > .four-image img { 
 
\t width: 100%; 
 
\t height: 100%; 
 
\t object-fit: cover; 
 
\t object-position: top center; /* To crop from the bottom */ 
 
}
<div class="four-grid-post"> 
 
\t <div class="cb-img-fw four-image"> 
 
\t \t <a href="postURL"><img src="http://placehold.it/400x300"></a> 
 
\t </div> 
 
\t <div class="cb-img-fw four-image"> 
 
\t \t <a href="postURL"><img src="http://placehold.it/400x200"></a> 
 
\t </div> 
 
\t <div class="cb-img-fw four-image"> 
 
\t \t <a href="postURL"><img src="http://placehold.it/300x400"></a> 
 
\t </div> 
 
</div>

+0

它完美的作品:D – Duannx