由于这个主题,我最近了解了 background-size
属性
Set size on background image with CSS?
正如您所猜到的,我正在尝试让背景图片占据整个屏幕,不多也不少。这是我的 fiddle
https://jsfiddle.net/1x7ytdaa/
document.body.style.backgroundImage = "url('http://www.crystalinks.com/ColosseumNight2.jpg')";
document.body.style.backgroundSize = "contain";
这是 contain
属性的作用
Scale the image to the largest size such that both its width and its height can fit inside the content area
图像的大小无关紧要。如果它更小,它应该缩放到屏幕的全尺寸。如果它较大,则应按比例缩小。
在 fiddle 中,您可以看到图像水平重复 5 次,垂直重复 5 1/2 次。
我已经尝试过 100% 100%
并且当宽度拉伸(stretch)整个屏幕时,它仍然在垂直方向上显示相同的图像 5 1/2 倍
我无法解释这种行为。有人有什么想法吗?
最佳答案
两件事:
- 背景重复
- body 的宽度和高度
正如您在 an edited fiddle 中所做的那样,问题是 background-repeat
的默认值是 repeat
。因此,图像将被重复而不是被拉伸(stretch)。不过,这并不能解决所有问题,因为 body 和 HTML 元素的宽度应定义为 100%。
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
document.body.style.backgroundImage = "url('http://www.crystalinks.com/ColosseumNight2.jpg')";
document.body.style.backgroundSize = "contain";
document.body.style.backgroundRepeat = "no-repeat";
如果要覆盖整个屏幕,请使用cover
而不是contain。 Cover 确保元素被完全覆盖,而 contain 只是确保背景图像被最大程度地包含(这可能会导致空白)。
关于javascript - 使用背景大小 CSS3 时非常奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38020732/