---
title: Build a responsive image tag helper
---

> **Documentation indexes**
> The indexes below list current page URLs with titles and descriptions. Links on this page point to the Markdown versions of the linked pages.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

## Build a responsive image tag helper

In the _Training guides_ repository, `ResponsiveImageTagHelper` (`<tg-responsive-image>`) outputs an `<img>` element with a responsive `srcset` based on the following design:

- **Width series from constants:** builds the `srcset` candidates from the _Scaled_ variant code names in `ImageVariants.WidthSeries`, using each variant's stored pixel width for the `w` descriptor.
- **Original image as the upper bound:** whenever a wider variant is excluded, the tag helper appends the original image at its own pixel width (unless a variant already matches that width), giving large screens full-resolution output with unique `w` descriptors.
- **Fallback for unoptimized assets:** if an asset has no generated width-series variants — such as an SVG, a GIF, or a newly migrated file — the tag helper outputs a plain `src` pointing to the original file.
- **Resolved application-relative URLs:** in Page Builder and preview mode, Xperience's HTML output filter only expands `~/` on the first URL in a `srcset` attribute. Passing every candidate URL through `IUrlHelper.Content` ensures valid URLs across all candidates in both administration and live-site views.

The first part of `ResponsiveImageTagHelper` defines the tag helper attributes and the `Process` method:

```csharp title="ResponsiveImageTagHelper.cs (public members)"
using System.Diagnostics.CodeAnalysis;
using System.Linq;

using CMS.ContentEngine;
using CMS.Helpers;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace TrainingGuides.Web.Features.ResponsiveImages.TagHelpers;

/// <summary>
/// Renders an <c>img</c> element for a <see cref="ContentItemAsset"/> using the responsive
/// <see cref="ImageVariants.WidthSeries"/> variants or a single <see cref="Variant"/> override.
/// Suppresses output when the asset is <c>null</c> or is not a supported image format.
/// </summary>
/// <param name="urlHelperFactory">Factory used to resolve app-relative asset URLs.</param>
[HtmlTargetElement("tg-responsive-image", TagStructure = TagStructure.WithoutEndTag)]
public class ResponsiveImageTagHelper(IUrlHelperFactory urlHelperFactory) : TagHelper
{
    private const string IMG_TAG = "img";

    /// <summary>
    /// View context injected by Razor for resolving application-relative URLs.
    /// </summary>
    [ViewContext]
    [HtmlAttributeNotBound]
    public ViewContext ViewContext { get; set; } = null!;

    /// <summary>
    /// The image asset to render.
    /// </summary>
    public ContentItemAsset? Asset { get; set; }

    /// <summary>
    /// Alternative text for the image; defaults to an empty string for decorative images.
    /// </summary>
    public string Alt { get; set; } = string.Empty;

    /// <summary>
    /// Optional variant code name to render as a single fixed image. Falls back to the
    /// responsive <c>srcset</c> when <c>null</c> or when the asset lacks the variant.
    /// </summary>
    public string? Variant { get; set; }

    /// <summary>
    /// The HTML <c>sizes</c> attribute describing the rendered image width per breakpoint.
    /// </summary>
    public string Sizes { get; set; } = "100vw";

    /// <summary>
    /// The HTML <c>loading</c> attribute (<c>lazy</c> by default, or <c>eager</c> above the fold).
    /// </summary>
    public string Loading { get; set; } = "lazy";

    /// <inheritdoc/>
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (Asset is null || !ImageHelper.IsImage(Asset.Metadata.Extension))
        {
            output.SuppressOutput();
            return;
        }

        output.TagName = IMG_TAG;
        output.TagMode = TagMode.SelfClosing;
        output.Attributes.SetAttribute("alt", Alt);
        output.Attributes.SetAttribute("loading", Loading);

        // Page Builder and preview only expand "~/" at the start of an attribute value,
        // so resolve every candidate URL before joining srcset.
        var urlHelper = urlHelperFactory.GetUrlHelper(ViewContext);

        if (TryGetVariant(Asset, Variant, out string? variantUrl, out var variantMetadata))
        {
            output.Attributes.SetAttribute("src", urlHelper.Content(variantUrl));
            SetDimensions(output, variantMetadata.Width, variantMetadata.Height);
            return;
        }

        var candidates = GetWidthCandidates(Asset);

        if (candidates.Count == 0)
        {
            output.Attributes.SetAttribute("src", urlHelper.Content(Asset.Url));
        }
        else
        {
            string srcset = string.Join(", ", candidates.Select(
                candidate => $"{urlHelper.Content(candidate.Url)} {candidate.Width}w"));

            output.Attributes.SetAttribute("src", urlHelper.Content(candidates[^1].Url));
            output.Attributes.SetAttribute("srcset", srcset);
            output.Attributes.SetAttribute("sizes", Sizes);
        }

        // Scaled variants preserve the original aspect ratio.
        SetDimensions(output, Asset.Metadata.Width, Asset.Metadata.Height);
    }

    ...
}
```

The private helper methods assemble the width candidates, look up variants by exact code name, and write the dimension attributes:

```csharp title="ResponsiveImageTagHelper.cs (private methods)"
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

using CMS.ContentEngine;

using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Razor.TagHelpers;

// ...

public class ResponsiveImageTagHelper(IUrlHelperFactory urlHelperFactory) : TagHelper
{
    ...

    /// <summary>
    /// Collects width-series variants that do not exceed the original image width, ordered
    /// from narrowest to widest, and appends the original image when wider variants were skipped.
    /// </summary>
    /// <param name="asset">The source image asset.</param>
    /// <returns>Candidate URLs and pixel widths, or an empty list if none are available.</returns>
    private static List<(string Url, int Width)> GetWidthCandidates(ContentItemAsset asset)
    {
        int originalWidth = asset.Metadata.Width ?? int.MaxValue;
        var candidates = new List<(string Url, int Width)>();
        bool seriesExceedsOriginal = false;

        foreach (string variant in ImageVariants.WidthSeries)
        {
            if (!TryGetVariant(asset, variant, out string? url, out var metadata)
                || metadata.Width is not int width)
            {
                continue;
            }

            if (width > originalWidth)
            {
                seriesExceedsOriginal = true;
                continue;
            }

            candidates.Add((url, width));
        }

        // Append the original only when its width is not already covered by the last variant,
        // since HTML srcset forbids duplicate width descriptors.
        if (seriesExceedsOriginal && (candidates.Count == 0 || candidates[^1].Width < originalWidth))
        {
            candidates.Add((asset.Url, originalWidth));
        }

        return candidates;
    }

    /// <summary>
    /// Looks up a variant's URL and dimension metadata by its exact, case-sensitive code name.
    /// </summary>
    /// <param name="asset">The source image asset.</param>
    /// <param name="codeName">The variant code name to look up.</param>
    /// <param name="url">When this method returns, contains the variant URL if found.</param>
    /// <param name="metadata">When this method returns, contains the variant metadata if found.</param>
    /// <returns>
    /// <c>true</c> if the asset contains both a URL and metadata for <paramref name="codeName"/>.
    /// </returns>
    private static bool TryGetVariant(
        ContentItemAsset asset,
        string? codeName,
        [NotNullWhen(true)] out string? url,
        [NotNullWhen(true)] out ContentItemAssetVariantMetadata? metadata)
    {
        url = null;
        metadata = null;

        // Both dictionaries are null when an asset has no variants, such as an SVG.
        return !string.IsNullOrEmpty(codeName)
            && asset.VariantUrls?.TryGetValue(codeName, out url) == true
            && asset.Metadata.Variants?.TryGetValue(codeName, out metadata) == true;
    }

    /// <summary>
    /// Writes <c>width</c> and <c>height</c> attributes when both dimensions are positive.
    /// </summary>
    /// <param name="output">The tag helper output to modify.</param>
    /// <param name="width">Width in pixels, or <c>null</c>.</param>
    /// <param name="height">Height in pixels, or <c>null</c>.</param>
    private static void SetDimensions(TagHelperOutput output, int? width, int? height)
    {
        if (width > 0 && height > 0)
        {
            output.Attributes.SetAttribute("width", width);
            output.Attributes.SetAttribute("height", height);
        }
    }
}
```

With `@addTagHelper *, TrainingGuides.Web` registered in `_ViewImports.cshtml`, you can invoke `<tg-responsive-image>` in your view by passing the asset, its alt text, and the `sizes` attribute for the layout:

```razor title="ImageVariantsShowcase.cshtml (responsive image)"
@using TrainingGuides.Web.Features.ResponsiveImages
@using TrainingGuides.Web.Features.ResponsiveImages.Models

@model ImageVariantsShowcaseViewModel

...
<tg-responsive-image asset="@image.Asset"
    alt="@image.AltText"
    sizes="(min-width: 1400px) 1296px, (min-width: 1200px) 1116px, (min-width: 992px) 936px, (min-width: 768px) 696px, (min-width: 576px) 516px, calc(100vw - 24px)"
    class="img-fluid" />
...
```

For the showcase's 4592 × 3064 px teaser photo, `<tg-responsive-image>` produces the following HTML. In the sample, `…` replaces the asset URL prefix and the file names are shortened for brevity:

```html
<img class="img-fluid" alt="Farfalle with basil pesto and fresh tomatoes served on a white plate" loading="lazy"
    src="…/ScaleW2560/eaters-collective_ScaleW2560.jpg?language=en"
    srcset="…/ScaleW480/eaters-collective_ScaleW480.jpg?language=en 480w,
        …/ScaleW828/eaters-collective_ScaleW828.jpg?language=en 828w,
        …/ScaleW1280/eaters-collective_ScaleW1280.jpg?language=en 1280w,
        …/ScaleW1600/eaters-collective_ScaleW1600.jpg?language=en 1600w,
        …/ScaleW1920/eaters-collective_ScaleW1920.jpg?language=en 1920w,
        …/ScaleW2560/eaters-collective_ScaleW2560.jpg?language=en 2560w"
    sizes="(min-width: 1400px) 1296px, (min-width: 1200px) 1116px, (min-width: 992px) 936px, (min-width: 768px) 696px, (min-width: 576px) 516px, calc(100vw - 24px)"
    width="4592" height="3064">
```

Because all six _Scaled_ variants are narrower than the 4592 px original, `srcset` includes the full series up to `2560w` and uses the `2560w` URL as the fallback `src`.

### Measure the sizes value in the real layout

The browser selects a candidate from `srcset` before applying the page's CSS layout. Consequently, the `sizes` [attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/img#sizes) must declare the image area's rendered width at each breakpoint ahead of time. Understating `sizes` causes the browser to download a blurry file, while overstating it wastes bandwidth. You can measure the exact widths directly on the rendered page:

1. Open the page in your browser's developer tools and use the device toolbar to set the viewport width one pixel below your layout's narrowest breakpoint.
2. Select the `<img>` element and record its rendered width in CSS pixels.
3. Repeat the measurement at each CSS breakpoint and one pixel below that breakpoint.
4. Combine the measurements into a comma-separated `sizes` string ordered from the widest breakpoint down, ending with a default width for the smallest viewports.

On the showcase page, the image sits inside a single-column Bootstrap container with 12 px of horizontal padding on each side. Below `576px`, the image area spans the viewport width minus `24px`; from `576px` upward, it matches each Bootstrap container width minus `24px`:

| Viewport width (px) | Image area width (CSS px) |
| ------------------- | ------------------------- |
| 320                 | 296                       |
| 575                 | 551                       |
| 576–767             | 516                       |
| 768–991             | 696                       |
| 992–1199            | 936                       |
| 1200–1399           | 1116                      |
| 1400 and wider      | 1296                      |

Those measurements translate directly into the showcase's `sizes` attribute:

```html noheader
(min-width: 1400px) 1296px, (min-width: 1200px) 1116px, (min-width: 992px) 936px, (min-width: 768px) 696px, (min-width: 576px) 516px, calc(100vw - 24px)
```

If you render the same image inside a narrower container — such as a sidebar or a multi-column grid — measure that container's widths and supply a matching `sizes` value.

### Check which file each screen downloads

To verify the result manually, open the page in your browser's developer tools, set the device toolbar to a high-DPI phone viewport, and reload the page with the **Network** tab open. Each `<img>` element's `currentSrc` property shows the variant URL selected by the browser, and the **Network** tab displays the transferred size. Repeat the check at a desktop viewport width with a device pixel ratio of 1.

On the showcase page, the `<tg-responsive-image>` element selects a different variant for each viewport:

- **Phone (390 px viewport, DPR 3):** the 366 px image area requires 1098 device pixels, and the browser downloads the 1280 px variant (210 KB).
- **Desktop (1440 px viewport, DPR 1):** the 1296 px image area requires 1296 device pixels, and the browser downloads the 1600 px variant (300 KB).

Both screens receive an image sharp enough for their pixel density. Because browsers select the next available width in `srcset` at or above the required pixel count, the step size between your width-series definitions determines the overhead (17% extra width on the phone and 23% on the desktop).

## Choose an approach for each image area

You can combine both rendering approaches in the same project while referencing variant code names from your shared constants class:

- **Built-in `kxp-img` tag helpers:** suited for fixed-size image areas (such as thumbnails or fixed-width cards) and `<picture>` elements that switch between distinct crops at specific breakpoints.
- **Custom `<tg-responsive-image>` tag helper:** suited for fluid image areas that scale across viewports and need a multi-width `srcset` to stay sharp on high-DPI phones and lightweight on desktops.

Start with `kxp-img` when a single crop or a `<picture>` breakpoint switch fits the layout, and use `<tg-responsive-image>` whenever an image area's width scales across viewports.

## Keep caching and generation in mind

Keep the following runtime behaviors in mind when serving image variants in production:

- **On-demand file generation:** Xperience generates each variant file the first time its URL is requested and serves the stored file on subsequent requests. An instance running in read-only mode generates first-requested variants into a temporary local cache instead; see [Read-only deployments](https://docs.kentico.com/documentation/developers-and-admins/deployment/read-only-deployments.md#content-item-asset-variants). Because every definition adds another generated file per requested image, keep your variant set limited to the dimensions used in your layouts.
- **Conditional revalidation by default:** Xperience's **Client cache (minutes)** setting defaults to _0_, which instructs browsers to revalidate every image request with the server. With the `ETag` header, the server responds to requests for unchanged files with a lightweight _304 Not Modified_ status.
- **Secured assets:** variants of secured content items include `Cache-Control: private`, which restricts caching to the visitor's own browser.
- **Longer client cache durations:** an image's variant URLs stay the same when an editor updates its focal point or crop. If you increase **Client cache (minutes)**, browsers may display a cached crop until the configured cache duration expires.

For more information on configuring client-side caching headers, see [File caching](https://docs.kentico.com/documentation/developers-and-admins/development/caching/file-caching.md).

> **Key:** **Key takeaways**
>
> - Pass `ContentItemAsset` alongside its alternative text in your view models, and set `LinkedItemsMaxLevel` high enough to load the referenced asset item.
> - Use Xperience's `kxp-img` tag helpers for single fixed crops and `<picture>` elements that switch crops across breakpoints, adding explicit `alt` and `loading` attributes and referencing variant code names from constants.
> - Use a custom responsive tag helper to output a multi-width `srcset` (capped at the original image width) paired with a `sizes` attribute measured from your page layout.
> - Verify which variant files the browser downloads on both high-DPI mobile and desktop viewports, and account for unchanged variant URLs when configuring client cache durations.
