GENERALLY NERDY RAMBLINGS

Responsive background images

An easily overlooked set of images on my wife’s web site that were significantly impacting network performance were the header background images.

These should be responsive to web site visitor’s device characteristics too.

The header ‘cover’ images - such as on the top of this page - presented a different challenge than the in-line images described in the previous post Here the page’s featured_image, used for the page summary is also used as the background for the page title and description.

For that I needed to learn the CSS equivalent of HTML5’s img srcset. The easiest solution ended being to create a Hugo partial that generates an inline style definition using CSS media queries. That background-img.html partial code is invoked in the layouts/partials/page-header.html like this

page-header-snippet.html

...
{{- $featured_image := .Param "featured_image" | default .Site.Params.featured_image -}}
{{- if $featured_image -}}
  {{- $featured_image := (path.Join "images" $featured_image) | absURL -}}
  {{ $.Scratch.Set "image" $featured_image }}
  {{- partial "background-img.html" . -}}
...

While the partial code ended up looking like:

Still some tweaking to do:

  • Lazy loading images
  • … Several other ideas percolating.