html – 具有“自动”高度的100%宽度背景图像(2015) – 跨浏览器

再问这个2013年线程( 100-width-background-image-with-an-auto-height)的答案似乎不再起作用了.

>我需要制作具有100%宽度和自动高度的响应式背景图像.
>我想使用媒体查询而不是Javascript根据屏幕大小提供不同的图像.
>如果它在不同的浏览器上运行会很好(至少Chrome / Firefox)

使用以下代码:

<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! :-(因为“内容”属性似乎与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

但这不是我想要做的,因为“封面”将允许图像从侧面伸出,“包含”不允许图像延伸出来.

这场噩梦的任何解决方案?

最佳答案 如果你不想使用媒体查询来改变背景图像,那么你的小提琴在我看来你试图通过使用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.

点赞