我需要我的背景图片来响应。我已经用过background-size: contain
了,而且似乎工作正常,但我也需要div的高度才能做出响应。
.container {
width: 100%;
}
.bg {
background: red url('https://cdn.pixabay.com/photo/2018/06/30/09/31/background-image-3507320_960_720.jpg') no-repeat center top;
background-size: contain;
height: 600px;
}
<div class="container">
<div class="bg"></div>
</div>
目前,高度为600像素,根据屏幕的宽度,您会看到红色背景,实际情况并非如此。
我已经尝试过background: cover
,但是它将缩放图像。它应为div的100%,但不应削减。
我该如何解决?
[我不是使用background-size: contain
,而是使用了background-size: auto
,它似乎可以按照您想要的方式工作。此外,我添加了一些JavaScript以帮助调整大小。
window.resize = function() {
var a = document.getElementById("a");
var b = document.getElementById("b");
a.style.width = "100%";
b.backgroundSize = "auto";
}
.container {
width: 100%;
}
.bg {
background: red url('https://cdn.pixabay.com/photo/2018/06/30/09/31/background-image-3507320_960_720.jpg') no-repeat center;
background-size: auto;
height: 600px;
}
<div class="container" id = "a">
<div class="bg" id = "b"></div>
</div>
您是否尝试过:
background-size: cover
这将使背景始终覆盖DIV-您可能需要周-->
background-position: xxxxx
[有时,您查看图像时使用的屏幕尺寸将意味着设置
@meda
查询以使其针对每种不同的欺骗(例如移动设备或台式机)正确使用
https://developer.mozilla.org/en-US/docs/Web/CSS/background-position
如果知道图像的比例,可以考虑填充技巧:
没有使用JavaScript的简单解决方案。只需将<svg>
以特定比例添加到容器中即可。