Thomi Thomi - 6 months ago 63
CSS Question

Responsive full width image banner with fixed height using srcset

I am trying to implement a responsive full width (fixed height) image banner with the

srcset
attribute.
To support older browsers i am using picturefill as a polyfill.

Basically i want a always 150px heigh full width banner, but with a different sized image depending von the
screen width
and the
device pixel ratio
.

The Problem is that
srcset
does not pick for example the
banner960x300
image if the
device pixel ratio
is 2.

Here is what i have tried:

<img srcset="/images/banner480x150.png 480w 1x,
/images/banner960x300.png 480w 2x,
/images/banner768x150.png 768w 1x,
/images/banner1536x300.png 768w 2x,
/images/banner992x150.png 992w 1x,
/images/banner1984x300.png 992w 2x,
/images/banner1200x150.png 1200w 1x,
/images/banner2400x300.png 1200w 2x,
/images/banner1920x150.png 1920w 1x,
/images/banner3840x300.png 1920w 2x"
sizes="100%"
class="banner"
style="width: 100%; height: 150px;">


and

<img srcset="/images/banner480x150.png 480w 150h,
/images/banner960x300.png 960w 300h,
/images/banner768x150.png 768w 150h,
/images/banner1536x300.png 1536w 300h,
/images/banner992x150.png 992w 150h,
/images/banner1984x300.png 1984w 300h,
/images/banner1200x150.png 1200w 150h,
/images/banner2400x300.png 2400w 300h,
/images/banner1920x150.png 1920w 150h,
/images/banner3840x300.png 3840w 300h"
sizes="100%"
class="banner"
style="width: 100%; height: 150px;">


I am not sure if this is the correct syntax for the
srcset
attribute.

Answer

I guess this is the solution:

<picture>
    <source media="(min-width: 1200px)" srcset="/images/banner1920x150.jpg 1x,
                                                /images/banner3840x300.jpg 2x">
    <source media="(min-width: 992px)" srcset="/images/banner1200x150.jpg 1x,
                                               /images/banner2400x300.jpg 2x">
    <source media="(min-width: 768px)" srcset="/images/banner992x150.jpg 1x,
                                               /images/banner1984x300.jpg 2x">
    <source media="(min-width: 480px)" srcset="/images/banner768x150.jpg 1x,
                                               /images/banner1536x300.jpg 2x">
    <img src="/images/banner480x150.jpg"
         srcset="/images/banner480x150.jpg 1x,
                 /images/banner960x300.jpg 2x"
         alt="Awesome banner"
         class="banner"
         style="width: 100%; height: 150px;>
</picture>

The relative 150px height is kept and the high resolution image is downloaded if the device pixel ratio is higher than 1x.

Comments