背景大小覆盖到img标签 [英] Background-size cover to img tag

查看:239
本文介绍了背景大小覆盖到img标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;

}

为什么background-size:cover在这里无效。这也应该在css3中添加,但不添加。

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?

我们可以使用 background:url(http://www.hdwallpapersplus.com) /wp-content/uploads/2013/06/abstract_color_background_picture_8016-wide.jpg)no-repeat; background-size:cover;

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;

推荐答案

你也可以使用jQuery做到这一点!

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%');

演示

这篇关于背景大小覆盖到img标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆