是否有可能对背景图像进行响应,因此在以下代码中按比例从桌面缩放到移动设备?
CSS :
div.backgroundimage {
background-image: url('images/image.jpg');
}
html :
<div class="backgroundimage"> </div>
请注意,我已经阅读了所有类似的问题,但没有按比例扩展的答案实施。我的意思是,有了一些示例,可以扩展宽度,但所有答复都缺少如何缩放高度。
谢谢!
您应该研究background-size
CSS属性。
background-size: 100%;
background-repeat: no-repeat;
background-size
属性接受各种类型的值,其中之一是
background-size: %width %height ;
如果仅通过一个值,则将另一个值设置为auto
。
注意: - 请记住,建议决定一个维度为基线,并将另一个维度设置为auto
。因为如果您设置两个维度,那么在大多数情况下,图像的纵横比将 skew 上升。
而不是使用背景图像属性,您可以创建一个图像,将缩放为窗口的尺寸,然后将其放在Div后面:
#background-image {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
}
您可以使用样式:
background-size: cover;
这应该保持长宽比(按比例缩放),但也覆盖了整个区域,宽度和高度。如果您想覆盖整个屏幕,则需要确保其具有完整的宽度和高度。
也可能是一个好主意。请参阅JSFIDDLE。
这将自动填充整个宽度和高度,但这意味着可能会在边缘上切断一些。另外,如果图像小于应该填充的内容,则看起来比看起来像素化(请参见下面的评论)。
我认为您需要JavaScript:
html:
<div></div>
css(全宽度):
div {
background: url(https://pixabay.com/static/uploads/photo/2015/07/17/06/08/styggkaerret-848532_960_720.jpg) no-repeat;
background-size: cover;
}
JS(全宽):
var ratio = 960 / 634; // width/height of the image
$(window).resize(function () {
var windowWidth = $(window).width();
$('div').css('height', windowWidth / ratio)
});
$(window).trigger('resize');
codepen(完整宽度)
css(不同宽度):
div {
background: url(https://pixabay.com/static/uploads/photo/2015/07/17/06/08/styggkaerret-848532_960_720.jpg) no-repeat;
background-size: cover;
max-width: 500px;
}
js(用于不同的宽度):
var ratio = 960 / 634; // width/height of the image
$(window).resize(function () {
var windowWidth = $(window).width();
$('div').css('height', $('div').width() / ratio)
});
$(window).trigger('resize');
codepen(不同的宽度)
html:
CSS:
.wrapper {
padding-bottom: 66.04%; // height/width*100%
max-width: 100%; // you can change it for example to 600px;
height: 0;
position: relative;
}
.bg {
background: url(https://pixabay.com/static/uploads/photo/2015/07/17/06/08/styggkaerret-848532_960_720.jpg) no-repeat;
background-size: cover;
width: 100%;
position: absolute;
}