Responsive images in Umbraco

Responsive images in Umbraco

Wednesday, March 30, 2016

When building websites in Umbraco, it's important to give editors the tools they need to author content, while keeping that content in line with the constraints set by the design. This isn't always easy. And if the design is responsive, it's even harder.

When modifying/hacking Umbraco to support responsive images, there's two steps you'll need to take; edit the back office JS and update your CSS. The changes needed in the back office differ between Umbraco 7.0.1 and Umbraco 7.0.4, but the CSS is the same, regardless of Umbraco version.

Umbraco 7.0.1

By default Umbraco uses TinyMCE as its rich textbox editor. When inserting images into the editor, TinyMCE will generate image tags with set height and width. Images with set height and width don't scale, so if you're developing a responsive website, TinyMCE just broke it.

Fixing this problem isn't that hard though. All we need is to edit the image plug-in for TinyMCE and declare some additional CSS.

tinymce.extend(args, { src: nl.src.value,
   // Removed width and height to enable responsive images (Umbraco 7.0.1).
   // width: nl.width.value,
   // height: nl.height.value,
   nl.alt.value,
   title: nl.alt.value,
   rel: nl.orgWidth.value + ',' + nl.orgHeight.value
});

Let's start with the image plug-in. Open up image.js, you'll find it in Umbraco_Client\Tinymce3\Plugins\Umbracoimg\Js\, and remove the two lines of code concerning height and width. Then save your changes.

Umbraco 7.0.4

$timeout(function () {
   var imgElm = editor.dom.get('__mcenew');
   var size = editor.dom.getSize(imgElm);
   var newSize = imageHelper.scaleToMaxSize(500, size.w, size.h);
   // Removed width and height (style) to enable responsive images (Umbraco 7.0.4).
   // var s = "width: " + newSize.width + "px; height:" + newSize.height + "px;";
   // editor.dom.setAttrib(imgElm, 'style', s);
   editor.dom.setAttrib(imgElm, 'rel', newSize.width + "," + newSize.height);
   editor.dom.setAttrib(imgElm, 'id', null);
}, 500);

Open up umbraco.services.js, you'll find it in Umbraco\Js\, and remove the two lines of code concerning the style attribute. Save you changes and clear the cache. The CDF cache is cleared by deleting the folder App_Data\TEMP\ClientDependency\ and recycling the application pool. Don't forget your browser cache. As soon as the cache has been cleared, the style attribute will no longer be set.

img {
   max-width: 100% !important;
   max-height: 100% !important;
   display: block;
}

Next, open up your style sheet and add the above CSS. You'll need to change the selector if you don't want all of you images to scale.

That's it. TinyMCE will no longer generate height and width attributes for image tags and your style sheet will make sure your images scale, keeping their aspect ratio.