具有 'auto' 高度的 100% 宽度背景图像 (2015) - 跨浏览器

100% width background image with an 'auto' height (2015) - Cross browser

作为 2013 年主题 (100-width-background-image-with-an-auto-height) 上的答案提出此问题似乎不再有效。

使用以下代码:

<img src="image.jpg" style="width: 100%;">

图像显示正确,100% 宽度和自动高度(参见此处:JSFIDDLE1)但是在更改屏幕尺寸时我无法替换它的来源,除非我使用Javascript.

因此我正在努力在 DIV 上使用背景图片。

<div class="imageContainer1"></div>

并且,使用以下 CSS,一切正常(至少在 Chrome/Safari 上):

.imageContainer1 {
    content:url("image.jpg");
}

看这里JSFIDDLE2

但是.. 这在 Firefox 上似乎不起作用! :-( 因为 "content" 属性 似乎与 firefox 不兼容。

所以....我想使用 "background-image" 属性,并找到一个与所有浏览器兼容的解决方案,但我正在努力设置 100% 宽度和自动高度.

这个

<div class="imageContainer2"></div>

.imageContainer2 {
    background-image: url("image.jpg");
    background-position: center top;
    background-size: 100% auto;
}

不显示任何内容,但如果您设置,例如:

height: 500px;

您将能够看到图片的一部分。

这是 JSFiddle:JSFiddle3

我试过使用:

background-size: cover/contain

但这不是我想要做的,因为 "cover" 将允许图像从侧面伸出,而 "contain" 根本不允许图像伸出)。

有解决这个噩梦的方法吗?

如果您不想大量使用 media queries 来更改 background-image,至于您的 fiddle,在我看来您只是想拥有使用 img 标签尽可能简单的代码,就像你提到的:

It would be good if it's working on different browsers (At least Chrome / Firefox)

所以..您可以在 img 标签中使用 srcset 属性,如下所示:

<img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w" alt="image">

srcset

A list of one or more strings separated by commas indicating a set of possible image sources for the user agent to use. Each string is composed of:

  1. a URL to an image,
  2. optionally, whitespace followed by one of:
    • a width descriptor, that is a positive integer directly followed by 'w'. The width descriptor is divided by the source size given in the sizes attribute to calculate the effective pixel density.
    • a pixel density descriptor, that is a positive floating point number directly followed by 'x'.

If no descriptor is specified, the source is assigned the default descriptor: 1x.

It is invalid to mix width descriptors and pixel density descriptors in the same srcset attribute. Duplicate descriptors (for instance, two sources in the same srcset which are bot described with '2x') are invalid, too.

User agents are given discretion to choose any one of the available sources. This provides them with significant leeway to tailor their selection based on things like user preferences or bandwidth conditions.