Re asking this as the answers on this 2013 thread (100-width-background-image-with-an-auto-height) don't seems to work anymore.
Using the following code:
<img src="image.jpg" style="width: 100%;">
The image is displayed correctly, 100% width and auto height (See here: JSFIDDLE1) but I am unable to replace the source of it when changing screen sizes, unless I use Javascript.
Therefore I am working on using a background image on a DIV.
<div class="imageContainer1"></div>
and, using the following CSS, everything works fine (at least on Chrome/Safari):
.imageContainer1 {
content:url("image.jpg");
}
See here JSFIDDLE2
but.. this doesn't seems to work on Firefox! :-( as the "content" property seems not to be compatible on firefox.
So.... I would like to use "background-image" property, and find a solution that is compatible with all the browsers but I am struggling with setting a 100% width and auto height.
This
<div class="imageContainer2"></div>
.imageContainer2 {
background-image: url("image.jpg");
background-position: center top;
background-size: 100% auto;
}
Doesn't show anything, but if you set, for example:
height: 500px;
you will be able to see a part of the picture.
This is the JSFiddle: JSFiddle3
I have tried to use:
background-size: cover/contain
But this is not what I am trying to do, as "cover" will allow the image to extend out from the sides and "contain" does not allow the image to extend out at all).
Any solution to this nightmare?
if you don't to want use media queries
a lot to change the background-image
, and as for your your fiddle it seems to me that you are trying to only have the code as simple as possible by using img
tag, and like you mentioned:
It would be good if it's working on different browsers (At least Chrome / Firefox)
So..you can use the srcset attribute in your img
tag, like this:
<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:
- a URL to an image,
- 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.