Wil Jones
Web Developer

Responsive Images using Srcset in Umbraco's Grid Editor


We know that the content editor can be dangerous, especially when it comes to adding images to a CMS. More often than not an editor does not want to optimise a jpg/png for the web, they will just upload the image they have, and forget about it. This image may be straight from a digital camera or a bought stock image. By default these examples will have file sizes of at least 4MB.

We have the image cropper in Umbraco, which we can easily configure to use in the grid. Simply set a config of the Image grid editor in /Config/grid.editors.config.js to specify a width and height and you will get a cropper in your grid. This solves the issue of loading a really large image, you can use the cropper to serve up the size you want.

What if you're showing this image in a full width column, but someone is viewing it on mobile? You're crop will be something like 1200px x 400px for example. (1200px from Bootstrap V3 desktop container width) If I view this on mobile I am still going to be downloading the 1200px x 400px image, but it will only display at 320px wide on my iPhone 4. This is a waste of bandwidth.

To solve this problem we need an image element, with some sources defined, so the browser can pick the best image to request for the width of the image on the page. For source set to work properly we need to tell the browser how big the image element is at different screen sizes. Consider a Bootstrap column with class col-sm-4. On screen sizes larger than 1200px this element will be approx (1140/3)px wide, using Bootstrap's default values for the size of the .container class.

Now we need to tell the image grid editor view about the column size that it is in. If you inspect the model that gets passed to the view, you'll find it only know about the data pertinent to the image. However this is a partial view, so we can pass a string-value dictionary into it. 

We know about the relative size of the column in /Views/Partials/Grid/Bootstrap3.cshtml, which then goes to /Views/Partials/Grid/Editors/Base.cshtml to work out what property editor view it should render. So we pass the columns number twice through to into /Views/Partials/Grid/Editors/Media.cshtml.

This is clearer in this Gist, https://gist.github.com/wjonesy/0ac2cd929c602517957e

  • Bootstrap3.cshtml - line 50, new ViewDataDictionary { { "grid", area.grid }
  • Base.cshtml - line 20,  new ViewDataDictionary { { "grid", Convert.ToInt32(ViewData["grid"]) } }
  • Media.cshtml - line 25, works out sizes based on Bootstraps .container widths. If you have container-fluid you will need to change this.

I used www.responsivebreakpoints.com to generate the 40 odd sources. I do not know if the amount of sources has a degradation on performance, I have not notices any performance issues so far.