100% Width Background Image with “Auto” Height (2015) - Cross Browser

I repeat this, since the answers to this thread in 2013 ( 100-width-background-image-with-an-auto-height ) no longer work.

  • I need to create a responsive background image with 100% width and auto height.
  • I would like to use different images depending on the screen size using media queries, not Javascript.
  • It would be nice if it worked in different browsers (at least Chrome / Firefox)

Using the following code:

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

The image is displayed correctly, the width is 100% and the height of the car (see here: JSFIDDLE1 ), but I can not replace the source when resizing the screen , if I do not 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 in Chrome / Safari):

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

See here JSFIDDLE2

but .. this does not seem to work on Firefox! :-( since the "content" property does not seem to be compatible with firefox.

So ... I would like to use the background-image property and find a solution compatible with all browsers, but I'm struggling with setting the width to 100% and the automatic height.

it

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

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

It does not show anything, but if you install, for example:

height: 500px;

You can see part of the image.

This is JSFiddle: JSFiddle3

I tried using:

background-size: cover/contain

But this is not what I am trying to do, since the “cover” will allow the image to be drawn from the sides and “contain” does not allow the image to be skipped at all).

Any solution to this nightmare?

+4
1

media queries background-image, , , img, , :

, ( Chrome/Firefox)

, srcset img, :

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

srcset

, , . :

  • URL- ,
  • , , :
    • , , 'w'. .
    • , , "x".

, : 1x.

srcset. (, srcset, "2x" ), .

. , , .

+1

Source: https://habr.com/ru/post/1619040/


All Articles