html
<div>
<img src="http://www.hdwallpapersplus.com/wp-content/uploads/2013/06/abstract_color_background_picture_8016-wide.jpg" />
</div>
css
div{
width: 200px;
height: 100px;
background-color: red;
}
img{
position: relative;
width: 100%;
height: 100%;
background-size: cover;
}
Why background-size: cover doesn't work here. This should also be added in css3, but not added. Is there anyway not to stretch the image?
As we can do it with background: url("http://www.hdwallpapersplus.com/wp-content/uploads/2013/06/abstract_color_background_picture_8016-wide.jpg") no-repeat; background-size: cover;
background: url("http://www.hdwallpapersplus.com/wp-content/uploads/2013/06/abstract_color_background_picture_8016-wide.jpg") no-repeat; background-size: cover;
Just set object-fit: cover;
on the img .
img { display: block; width: 200px; height: 100px; object-fit: cover; }
<img src="http://www.hdwallpapersplus.com/wp-content/uploads/2013/06/abstract_color_background_picture_8016-wide.jpg" />
You can read more about this new property in this webplatform article .
From the above article - regarding the 'cover' value:
The whole image is scaled down or expanded till it fills the box completely, the aspect ratio is maintained. This normally results in only part of the image being visible.
Also, here is a fiddle from the above article which demonstrates all the values of the object-fit
property.
img { position: relative; width: 0; height: 0; padding: 50px 100px; background: url(http://www.hdwallpapersplus.com/wp-content/uploads/2013/06/abstract_color_background_picture_8016-wide.jpg) no-repeat; background-size: cover; }
<img src="http://www.hdwallpapersplus.com/wp-content/uploads/2013/06/abstract_color_background_picture_8016-wide.jpg" />
Don't worry! You can do this too using jQuery!
var imgSrc=$('div img').attr('src');
$('div img').remove();
$('div').html('<div class="backbg"></div>');
$('.backbg').css('background-image', 'url(' + imgSrc + ')');
$('.backbg').css('background-repeat','no-repeat');
$('.backbg').css('background-size','cover');
$('.backbg').css('width','100%');
$('.backbg').css('height','100%');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.