If you enjoy reading my blog, you could consider supporting me on Patreon.

Responsive images as CSS background

Integrating the Responsive Images spec together with CSS backgrounds, allowing for more flexibility for eg. hero images because you can use background-size: cover; etc., and still have the full benefits of responsive image loading.

        img {
        img.loaded {
            display: none;
        .responsive-image {
            background-size: cover;
            background-position: center;
    <div class="responsive-image">
        <img src="./small.jpg" srcset="./large.png 3000w, ./medium.jpg 1920w, ./small.jpg 425w" >
        document.addEventListener('DOMContentLoaded', function() {
            const images = document.querySelectorAll('.responsive-image');
            [].forEach.call(images, function (imageContainer) {
                const image = imageContainer.querySelector('img');
                image.addEventListener('load', function () {
                    if (!image.currentSrc) {
                    imageContainer.style['background-image'] = "url('" + image.currentSrc + "')";

This is where the ad would go. I get it, they are stupid. But to be honest, they actually make a difference. So maybe you'd consider whitelisting this blog or support me on Patreon?