我有

body {
    background: url(images/background.svg);
}

理想的效果是,这个背景图像的宽度将与页面的宽度相等,高度改变以保持比例。例如,如果原始图像刚好是100*200(任何单位),主体宽度为600px,背景图像最终应该是1200px高。如果窗口调整大小,高度应该自动改变。这可能吗?

目前,Firefox看起来像是先调整高度,然后再调整宽度。这可能是因为高度是最长的维度,它试图避免裁剪?我想垂直裁剪,然后滚动:没有水平重复。

此外,Chrome将图像放置在中心,没有重复,即使是明确给出background-repeat:repeat,这是默认的。


当前回答

以下是对我有效的方法:

background-size: auto 100%;

其他回答

只要加上这一行:

    .your-class {
        height: 100vh;
    }

Vh为视口高度。 这将自动缩放以适应设备的浏览器窗口。

查看更多在这里:使div 100%的高度浏览器窗口

试试这个,

element.style {
    background: rgba(0, 0, 0, 0) url("img/shopping_bgImg.jpg") no-repeat scroll center center / cover;
}

我也遇到了同样的问题,在调整浏览器尺寸时无法调整图像大小。

糟糕的代码:

html {  
  background-color: white;  
  background-image: url("example.png");  
  background-repeat: no-repeat;  
  background-attachment: scroll;  
  background-position: 0% 0%;
}

好的代码:

html {  
  background-color: white;  
  background-image: url("example.png");  
  background-repeat: no-repeat;  
  background-attachment: scroll;  
  background-position: 0% 0%;
  background-size: contain;
}

这里的关键是添加这个元素-> background-size: contains;

  width: 100%;
  height: 100vh;
  background: url("../img/hero-bg.jpg") top center;
  background-size: cover;
  background-repeat: no-repeat;  
  background-position: 0% 0%;
  background-size: 100% 100%;

根据https://developer.mozilla.org/en-US/docs/CSS/background-size上的建议,我总结出了以下对我有用的食谱

body {
        overflow-y: hidden ! important;
        overflow-x: hidden ! important;
        background-color: #f8f8f8;
        background-image: url('index.png');
        /*background-size: cover;*/
        background-size: contain;
        background-repeat: no-repeat;
        background-position: right;
}