html - 100% 宽度背景图片,高度为 'auto' (2015) - 跨浏览器

标签 html css background background-image responsiveness

作为 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

但这不是我想要做的,因为“cover”会让图像从侧面延伸出来,而“contain”根本不允许图像延伸出去。

这个噩梦有什么解决办法吗?

最佳答案

如果你不想大量使用media queries来改变background-image,至于你的 fiddle ,在我看来你正在尝试通过使用 img 标签让代码尽可能简单,就像你提到的那样:

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

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

<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.

关于html - 100% 宽度背景图片,高度为 'auto' (2015) - 跨浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34157533/

相关文章:

jquery - 使用 fadeIn() 效果加载图像背景

上传图片时,jquery.form.js 在 IE 中不起作用

javascript - css网格系统中的模态定位

css - 如何让网格区域有文档流?

html - Twitter Bootstrap,样式化和使用媒体网格类

ios - 如何在 Ionic 应用程序中添加后台服务

CSS:如何制作带有 repeat-x 背景和提示的 !100% 标题

html - 定制贴 "Back to Top"链接

html - Div 在所有其他 div 之上

css - 一种自动将内容流入列的方法?