Page editor support in Sitecore for css background images

While displaying images on your site, sometimes it is preferable to use css style background images instead of the img tag.
Some of the reasons I have located for this:

  • It lets you have actual text in the element (offset with CSS so people can’t see it) instead of an alt attribute which is theoretically better food for search engines.
  • It also lets you use sprites (background images containing multiple pictures which are cropped with background-position, height and width) to reduce the numbers of HTTP requests being made for images.
  • Use background-image if you intend to have people print your page and you do not want the image to be included by default.
  • Use background-image if you need for only a portion of the image to be visible, as with CSS sprites.
  • Use background-image with background-size:cover in order to stretch a background image to fill its entire window.
  • Use CSS background images when doing image-replacement of text eg. paragraphs/headers.
  • Use CSS background images if the image is not part of the content.

When we use background images, how do we get page editor support for such images?

One great solution would ofcourse be using Sitecore EditFrames. (EditFrame with Sitecore MVC and Glass.Mapper)

But – this does involve creating additional items in the Core DB, especially if you have different field names for the image fields.
If you wanted to bypass this step, here’s a solution!

For every background image you render – make sure you add a couple of lines for the scenario when this page is loaded in page editor mode:


<figure class="page-banner" style="background-image: url('/en/sitecore/shell/~/media/images/banners/startup.jpg')">
    @if (Sitecore.Context.PageMode.IsPageEditor)
    {
        @RenderImage(m => m.Background_Image, new { @class = "page-editor-editable-image" }, isEditable: true)
    }
</figure>

You just need to make sure that this page editor friendly image (with the special class we define) is on the top of all your content – layer wise (Settings z-index:-1;position:relative to the remaining content will ensure this).

2015-11-01_070436

Once this is done, here’s how your image will appear in page editor mode:

2015-11-01_064908

Advertisements

2 thoughts on “Page editor support in Sitecore for css background images

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s