Images in Sitecore and Responsive Design

Recently, I teamed up with a group of front end developers on a project to launch a fully responsive web site. Things were going smoothly until the content entry portion of the project started. I started to get ticket after ticket in my queue, “Matt can you go in and remove the inline height and width on this img tag?” Sure enough, when viewed in tablet or mobile mode, the images were rendering awkwardly. The first couple I looked at were coming from a rich text field, so it wasn’t a big deal to go in to Sitecore and remove the size attributes. But then I noticed that the <sc:FieldRenderers> and <sc:Image> also had the height and width inline. Wuh oh.... At this point, I knew I would need a global fix. Sitecore was, by default, grabbing the height and width from the media library item in Sitecore and inserting it in to the html.

Because the style of the entire site was being handled by the responsive CSS and JS created by the front end developers – there seemed to be no reason to ever have the height and width included in any of the <img> tags. I thought about this for a bit and was proud of my solution. I created a class which modified the renderField pipeline and grabbed any image from Sitecore and removed the height and width attributes. I included a patch in my SitecoreSettings.Config file to reference my class and just like that all the images on the site were rendering much better.

I ran this fix by a colleague who seemingly punched me in the stomach. “What if the client needs to put the height or width in the image? What if they create another site within the solution that isn’t responsive? Why would you want to take a feature like this away from the CMS?” It took a minute to sink in, but he was right. While I needed to remove these attributes, a site-wide sweep was not the way to do it. Instead, I went back and made each <sc:image> item a <asp:image> item instead. In the codebehind, I assigned the image url like so:

ImageUrl = stringUtil.EnsurePrefix('/',mediaManager.GetMediaUrl(item.IssueImage.MediaItem));

What this did was strip the height and width that was coming in from the MediaItem itself but still allowed the Content Editor to add the height and width to the property field where they inserted the image.

Although going through the entire solution to change the code was no small task, it was the better solution that offered more flexibility to the client. Having the solution work while still giving the Content Editor the ability to do what they need and leaving room for flexible growth is always the best solution.