Implementing full-width responsive background images with srcset and lazy loading for optimal performance

I'm currently developing a website with a striking layout featuring 'hero' panels that cascade down the home page, showcasing text overlaid on captivating background images.

My goal is to utilize inline images with srcset and sizes attributes in order for the browser to select the most suitable image based on screen size rather than simply inserting the largest image possible as a background-image and scaling it down for smaller screens.

At this point, here's what my code looks like:

<img 
  src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" 
  srcset="/img/trekking_320.jpg 320w,
          /img/trekking_480.jpg 480w,
          /img/trekking_600.jpg 600w,
          /img/trekking_768.jpg 768w,
          /img/trekking_960.jpg 960w" 
  data-sizes="100vw"
  class="lazyload"
>

along with CSS:

img {
  position: absolute;
  height: 100%; width: auto;
}

with overflow:hidden set on the container element.

The image heights range from 320px to 768px, then 480px up to 960px, followed by a max-height of 600px beyond that.

I've prepared a Codepen demonstration to showcase the issue. While everything functions smoothly on high-resolution screens across various devices (mobile, tablet, laptop) and even on standard dpi displays up to 768px wide, there seems to be an issue with the images not filling the screen past that point.

Given the circumstances, I'm left pondering if it's feasible to achieve all the mentioned requirements outlined in the title. Am I heading in the right direction, or should I explore an entirely different approach?

Answer №1

Avoid misusing <img /> tags for background images and instead utilize CSS background-image (along with background-size: cover or fill for a responsive appearance). Employ the image-set function to define various images for different device screen resolutions:

As of August 2021, note that image-set is unsupported by Firefox/Gecko, Internet Explorer, and Edge - exclusively compatible with WebKit-based browsers like Chrome, Safari, and Opera. More details can be found at:

body {
    background-image: -webkit-image-set(
        url('path/to/image') 1x,
        url('path/to/high-res-image') 2x,
        etc...
    );
    background-size: cover;
}

Answer №2

After struggling with this issue myself, I was surprised to discover that even in the year 2024, there is still no straightforward solution for serving smaller background images on smaller screens. While the image-set property is a step in the right direction, it falls short due to its limitation to the pixel density descriptor (x) and lack of awareness of the screen's width (unlike the <img> srcset w descriptor). Inline media queries in an element's style attribute are not possible either. Resorting to an absolutely positioned <img> or <picture> for a background image can be cumbersome and make it challenging to cover a resizable box effectively. The workaround I've devised involves generating a separate <style> block for the desired <header>:

def banner_background(page, widths=[1200,800], switch=900, ratio=2.33)
    banner = page.images.banner.first
    style = ""
    if banner.present?
        style += "article > header {"
        style += "background-image: url(\"#{url_for(banner.image_file.variant(resize_to_fill: [widths[0], widths[0]/ratio]))}\");"
        style += "} @media (max-width: #{switch}px) { article > header {"
        style += "background-image: url(\"#{url_for(banner.image_file.variant(resize_to_fill: [widths[1], widths[1]/ratio]))}\");"
        style += "}}"
    end
    style.html_safe
end
<style><%= banner_background(page) %></style>
<header>
...

While this approach may seem awkward, it does offer a significant advantage over other methods - it works efficiently and reduces the download size for my header backgrounds by half, saving about 60 kB per image. Although plans for w and h support in image-set are in place, until widespread adoption, we're left grappling with workarounds like this one. If anyone has a better suggestion, I'm all ears!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to eliminate the default background color applied to the body automatically?

I'm currently developing a Covid-19 tracking web application and I am using chartJS to showcase data from an API. In my CSS, I have assigned a background color to all elements with an asterisk (*), but for some reason there are empty spaces around the ...

Ways to slightly boost the default font-size values when using wicked-pdf

In the wicked-pdf report, I have body content with varying font sizes. When I apply a font-size of 16px to the paragraph like so: p { font-size: 16px !important; } The entire paragraph's font size becomes 16px, which may include words with diff ...

Tab button that can be easily printed

I'm currently facing a challenge with my HTML code on my website. I have 5 tabs already set up, but I want to add one that redirects users to a printable page that opens the print menu specific to their browser. It seems like there might be an issue i ...

Ways to make JavaScript cycle through a set of images

I'm having trouble trying to set up a code that will rotate multiple images in a cycle for an image gallery I'm working on. So far, I've only been able to get one image to cycle through successfully. Any help or suggestions would be greatly ...

Maintain the structure of the slick slider during transitions

I am working with the slick slider and aiming to achieve a specific layout for the slider itself. What I require is a structure that looks like this: div div div div div I have managed to implement this design successfully, bu ...

Previewing Jquery script with live interactive effect using Javascript

Looking to create a page where a sentence can be written and displayed in a well-designed format on the right using Jquery live preview. However, currently the design only loads after writing and reloading the page. Any suggestions on how to generate the ...

I am struggling to retrieve information from HTML elements using the GET method in Node.js and MongoDB

Code Troubleshooting var userID = req.userid; var pwd = req.pwd; console.log("userid = " + userID + "pass = " + pwd); The console is displaying undefined values instead of the input data. I have a problem with fetching data from an HT ...

Can a class be passed to the binding attribute in Angular framework?

We currently have a system in place that is dependent on a numeric value being set to either 1 or 2 in order to display specific icons. This method is functional. <span *ngIf="config.icon" [class.fas]="true" [class.fa-plus]="icon===1" ...

Tips for concealing a parent element while inside a span with jquery

Beginner asking for help! Take a look at what I've coded: <div class="Links"> <a href="/testthis1.html" data-id="button1"> <img class="icon" src="/test1.png" alt="test1"> <span>Test 1</span> < ...

Is there a different method to position an element in the center of the webpage?

Typically, the code margin:auto is used for centering, but I have a different code below. HTML : <article> <header></header> </article> CSS: article{ max-width: 500px; margin: auto; /* centered - nice */ } header{ width: ...

Ways to incorporate bold, unbold, and italic styles into a single heading text within the same line using Bootstrap 4

Is there a way to format a single line of text with certain words bolded and the rest regular? I have a specific example pictured here: Picture of my Issue Specifically, I'm looking to bold "Honors:" and "Capstone:", while keeping the surrounding tex ...

Text To Appear Gradually When Button Is Clicked

Is it possible to create a fading effect for text when a button is clicked? Currently, my code displays some text as block while hiding the rest with display:none. Take a look at my JavaScript code: <script> //Select button by id const btn1 ...

Modifying webpage code

I am looking to develop a system where I can edit various elements such as the navbar, paragraphs, and images directly from a web page. I understand that this can be achieved with JavaScript, but I am facing the issue of my customizations reverting to defa ...

Unable to move up and down in my iframe

I am currently working on an Instagram page that is visible through an iframe. Everything seems to be functioning fine on my iMac, but I am facing an issue with scrolling on my iPhone and iPad? After reviewing my code, I couldn't find any hidden over ...

How can I exclude specific lines from an XML file using filters?

Let's say I have the following data: <div class="info"><p><b>Orange</b>, <b>One</b>, ... <div class="info"><p><b>Blue</b>, <b>Two</b>, ... <div class="info"><p><b& ...

Scroll sideways with AJAX content replacement

I've successfully discovered various methods for loading and replacing content with ajax, as well as ways to hide/show with effects. However, I'm now seeking a technique that allows the new content to slide into a div while the old content slide ...

Guide: Previewing uploaded images with HTML and jQuery, including file names

Any constructive criticism and alternative methods for accomplishing this task are welcomed. I am currently working on writing jQuery code that will allow users to preview file(s) without reloading the DOM. To achieve this, I have been using .append() to ...

Issues with properly triggering re-clicking events in AngularJS when using Bootstrap modal

I am currently utilizing Angular JS in combination with Bootstrap modal. Below is the Anchor link I am referring to: <li><a href="#" data-toggle="modal" data-target="#inviteFriendModal" ><span class="frndInvt"></span>Invite Friends ...

Is there a way to prevent my cell from resizing during the initiation of a jQuery animate effect?

After coding a 2x2 DIV table, I encountered an issue where the left side of the cell appears when hovering over the right cell. However, the left cell is hidden when the mouse leaves the right cell, utilizing a jQuery animate effect. I'm facing a pro ...

Tips on preventing the constant shifting of my webpage div elements when resizing the browser

Whenever I resize my webpage browser, the 3 text input boxes move and overlap, causing the page layout to become messy. View of The Browser in full screen (normal) View of The Browser when it's smaller (not normal) As a beginner programmer, I have ...