---
title: Render image variants in views and components
---

> **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).

Your Razor views control which image variant the browser downloads for each placement on a page. A single uploaded photo can appear as a square crop on a phone, a wide hero banner on a desktop monitor, and a compact 4:3 card in a listing grid.

By the end of this material, you'll pass image assets and their variants into your view models, render fixed crops and hero banners that switch crops using the built-in Xperience by Kentico tag helpers, and create a custom `<tg-responsive-image>` tag helper that outputs a multi-width `srcset`.

![The Image variants showcase page at a 1440 px wide viewport: a wide hero banner across the top, a 4:3 card below it, and a container-wide responsive image under that, all three showing the same photo of farfalle with pesto.](https://docs.kentico.com/docsassets/guides/render-image-variants-in-views/Showcase_Page_1440.jpg "The image variants showcase at a 1440 px viewport")

## Before you start

This material builds on the principles described in [Plan your image variant set](https://docs.kentico.com/guides/development/image-variants/plan-your-image-variant-set.md). Make sure you have the following:

- Image variant definitions configured in your instance, with their code names stored as constants in a shared class such as `ImageVariants` in the _Training guides_ repository.
- Familiarity with [content item assets](https://docs.kentico.com/documentation/business-users/content-hub/content-item-assets.md), the [content retriever API](https://docs.kentico.com/documentation/developers-and-admins/api/content-item-api/content-retriever-api.md) and [tag helpers in Xperience](https://docs.kentico.com/documentation/developers-and-admins/development/reference-tag-helpers.md).
- A running instance of Xperience by Kentico, preferably [31.7.2](https://docs.kentico.com/changelog.md) or higher.

  > **Note:** Some features covered in the Training guides may not work in older versions.

> **Info:** **Code samples**
>
> You can find a project with completed, working versions of code samples from this guide and others in the [finished branch](https://github.com/Kentico/xperience-by-kentico-training-guides/tree/finished) of the _Training guides_ repository.
>
> The [main branch](https://github.com/Kentico/xperience-by-kentico-training-guides) of the repository provides a starting point to code along with the guides.
>
> The code samples in this guide come from a project that targets [.NET 10](https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10/overview) and uses [implicit using directives](https://learn.microsoft.com/en-us/dotnet/core/project-sdk/overview#implicit-using-directives). You may need to add additional `using` directives to your code if your project does not use this feature.

## Explore the showcase

In the _Training guides_ repository, the _Image variants_ page (under _News and articles_) uses the _Image variants showcase_ page template to render the same article teaser photo in three different layouts:

- A hero banner that switches from a square crop on phones to a wide landscape crop on larger viewports.
- A card with a fixed 4:3 crop.
- A responsive image that scales with its image area width and the screen's pixel density.

The implementation lives under `Features/ResponsiveImages` in the `TrainingGuides.Web` project, with view models in `Models`, the tag helper in `TagHelpers` and the showcase view component in `ViewComponents`. The page template renders the showcase view component above its main editable area:

```razor title="ImageVariantsShowcasePageTemplate.cshtml"
@using TrainingGuides.Web.Features.Articles

@model TemplateViewModel

...
<vc:image-variants-showcase />
<div>
    <editable-area area-identifier="areaMain" />
</div>
```

Although the showcase uses a view component inside a [page template](https://docs.kentico.com/documentation/developers-and-admins/development/builders/page-builder/page-templates-for-page-builder.md), the same tag helpers work in any Razor view covered by your `@addTagHelper` directive, including standard MVC views, Page Builder widgets, and sections.

## Pass the asset to the view

### Carry the asset and its alt text

When Xperience maps an asset field onto a generated content type class, it populates a `ContentItemAsset` property directly from the item's stored metadata. That object carries the original file URL, the dictionary of variant URLs (`VariantUrls`), and the stored pixel dimensions (`Metadata`) for both the original image and each variant.

Because Xperience's built-in `kxp-img` tag helpers accept a `ContentItemAsset` instance, include the `ContentItemAsset` object directly on your view models so your views have access to every variant URL and its stored dimensions.

`ContentItemAsset` only describes the file binary and its variants; alternative text lives in a separate field on the content type, such as `AssetAltText` on the _Asset_ type in the _Training guides_ repository. Define a small record that pairs `ContentItemAsset` with its alt text:

```csharp title="ImageViewModel.cs"
using CMS.ContentEngine;

namespace TrainingGuides.Web.Features.ResponsiveImages.Models;

/// <summary>
/// Pairs an image asset with its alternative text for rendering in views.
/// </summary>
/// <param name="Asset">The image asset, including its variant URLs and dimension metadata.</param>
/// <param name="AltText">Alternative text for the image, or an empty string for decorative images.</param>
public record ImageViewModel(ContentItemAsset Asset, string AltText)
{
    /// <summary>
    /// Creates an <see cref="ImageViewModel"/> from an <see cref="Asset"/> content item.
    /// </summary>
    /// <param name="asset">The source Asset content item, or <c>null</c>.</param>
    /// <returns>
    /// A populated <see cref="ImageViewModel"/>, or <c>null</c> if the item or its file is missing.
    /// Null alternative text is normalized to an empty string.
    /// </returns>
    public static ImageViewModel? GetViewModel(Asset? asset) => asset?.AssetFile is null
        ? null
        : new(asset.AssetFile, asset.AssetAltText ?? string.Empty);
}
```

`ImageVariantsShowcaseViewModel` holds the article's `Title` and an optional `ImageViewModel?`, which remains `null` if the page has no linked article or teaser asset.

### Retrieve the image with enough linked-item depth

On an article page, the teaser image is two reference hops away from the page itself: `ArticlePage` references the article content item (`ArticlePageArticleContent`), which in turn references the reusable _Asset_ item (`ArticleSchemaTeaser`).

![Content model of the image variants showcase. The ArticlePage page content type, retrieved by RetrieveCurrentPage, is level 0. Its ArticlePageArticleContent field references an article item that implements IArticleSchema, a GeneralArticle or Interview, at level 1. The article's ArticleSchemaTeaser field references an Asset item of a reusable content type, with the AssetFile field holding the image and its variants and the AssetAltText field, at level 2. Each reference adds one level.](https://docs.kentico.com/docsassets/guides/render-image-variants-in-views/Image_Variants_Showcase_Content_Model.drawio.svg "Content model of the image variants showcase")

When querying content with `RetrieveCurrentPage`, linked-item depth starts at level 0 for the page itself and increments by one for each reference hop. Reaching the _Asset_ item therefore requires a maximum linked-item level of `2`. At depth `1`, the query loads the article item and leaves its `ArticleSchemaTeaser` property `null`.

In the _Training guides_ repository, `IContentItemRetrieverService.RetrieveCurrentPage` forwards its depth argument to `RetrieveCurrentPageParameters.LinkedItemsMaxLevel`. `ImageVariantsShowcaseViewComponent` requests depth `2` to load the teaser asset:

```csharp title="ImageVariantsShowcaseViewComponent.cs"
using System.Linq;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Mvc;

using TrainingGuides.Web.Features.ResponsiveImages.Models;
using TrainingGuides.Web.Features.Shared.Services;

namespace TrainingGuides.Web.Features.ResponsiveImages.ViewComponents;

/// <summary>
/// Renders the current article page's teaser image using both the built-in Xperience
/// image tag helpers and the custom responsive image tag helper.
/// </summary>
/// <param name="contentItemRetrieverService">Service used to retrieve the current page.</param>
public class ImageVariantsShowcaseViewComponent(
    IContentItemRetrieverService contentItemRetrieverService)
    : ViewComponent
{
    // Level 0: ArticlePage -> Level 1: article item -> Level 2: teaser Asset item.
    private const int TEASER_ASSET_DEPTH = 2;

    /// <summary>
    /// Retrieves the current article page and maps its title and teaser image.
    /// </summary>
    /// <returns>The showcase view result.</returns>
    public async Task<IViewComponentResult> InvokeAsync()
    {
        var articlePage = await contentItemRetrieverService
            .RetrieveCurrentPage<ArticlePage>(TEASER_ASSET_DEPTH);
        var article = articlePage?.ArticlePageArticleContent.FirstOrDefault();

        var model = new ImageVariantsShowcaseViewModel
        {
            Title = article?.ArticleSchemaTitle ?? string.Empty,
            Image = ImageViewModel.GetViewModel(article?.ArticleSchemaTeaser.FirstOrDefault())
        };

        return View("~/Features/ResponsiveImages/ViewComponents/ImageVariantsShowcase.cshtml", model);
    }
}
```

Fetching the page inside the view component lets the showcase page template work alongside any controller that serves `ArticlePage`. In your own page controllers, you can map `ImageViewModel` directly onto the page view model and pass it down to your views.

For more details on linked content retrieval, see [Retrieve linked content items](https://docs.kentico.com/documentation/developers-and-admins/development/content-retrieval/retrieve-content-items.md#retrieve-linked-content-items).

> **Note:** If you restrict a query's columns with `Columns(...)`, always include `ContentItemGUID` and `ContentItemCommonDataContentLanguageID`. Xperience requires both columns when constructing a `ContentItemAsset`.

## Render variants with the Xperience tag helpers

The `kxp-img` attribute [tag helpers](https://docs.kentico.com/documentation/developers-and-admins/development/reference-tag-helpers.md) render a single image variant on an `<img>` element or on a `<source>` element inside `<picture>`:

- `kxp-img-variant` – accepts a variant code name and writes that variant's URL to `src` (on `<img>`) or `srcset` (on `<source>`). Referencing code names from your constants class prevents typos at compile time.
- `kxp-img-dimensions` – outputs the variant's stored `width` and `height` attributes so the browser reserves layout space ahead of the image download.

Because the `kxp-img` tag helpers only manage `src`/`srcset`, `width`, and `height`, always include explicit `alt` and `loading` attributes on the `<img>` element.

### Switch crops on phones with a picture element

A wide 16:9 hero banner often crops out the subject when scaled down to a narrow phone screen. Using a `<picture>` [element](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/picture), you can serve a square crop below a mobile breakpoint and the wide crop on larger viewports:

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

@model ImageVariantsShowcaseViewModel

@if (Model.Image is { } image)
{
    ...
    <picture>
        <source media="(max-width: 575.98px)"
            kxp-img="@image.Asset"
            kxp-img-variant="@ImageVariants.HERO_MOBILE_828X828"
            kxp-img-dimensions="true" />
        <img kxp-img="@image.Asset"
            kxp-img-variant="@ImageVariants.HERO_WIDE_1920X1080"
            kxp-img-dimensions="true"
            alt="@image.AltText"
            loading="eager"
            class="img-fluid" />
    </picture>
    ...
}
```

Because the hero banner is the primary above-the-fold image on the page, set `loading="eager"` on the inner `<img>` element. The `<source>` element supplies the mobile crop for viewports under `576px`, while the `<img>` element provides the default desktop crop along with the shared `alt` and `loading` attributes.

![The hero banner of the showcase at a 1440 px wide viewport: the HeroWide1920x1080 crop shows a white plate of farfalle with basil pesto and cherry tomatoes on the right and the bare tabletop on the left.](https://docs.kentico.com/docsassets/guides/render-image-variants-in-views/Showcase_Hero_Wide_1440.jpg "Wide crop of the hero at a 1440 px viewport")

![The same hero at a 390 px wide viewport: the HeroMobile828x828 square crop fills most of the frame with the pasta and tomatoes, with only a strip of tabletop on the left.](https://docs.kentico.com/docsassets/guides/render-image-variants-in-views/Showcase_Hero_Phone_390.jpg "Square crop of the hero at a 390 px viewport")

### Show a fixed crop in a card

For a card component with a fixed aspect ratio, apply `kxp-img` and `kxp-img-variant` directly to an `<img>` element, and set `loading="lazy"` for cards rendered below the fold:

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

@model ImageVariantsShowcaseViewModel

...
<div class="c-card_img">
    <img kxp-img="@image.Asset"
        kxp-img-variant="@ImageVariants.CARD_800X600"
        kxp-img-dimensions="true"
        alt="@image.AltText"
        loading="lazy"
        class="img-fluid" />
</div>
...
```

> **Warning:** `kxp-img-variant` performs a case-sensitive lookup against the asset's variants. If the specified code name does not match a variant on the asset, the tag helper silently falls back to the full-size original image URL and omits the `width` and `height` attributes.

## 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.

## What's next

With `<tg-responsive-image>` in place, you can let editors choose which variant to display per widget instance in Page Builder. To build the _Image_ widget and its **Image size** setting, continue with [Let editors select image variants](https://docs.kentico.com/guides/development/image-variants/let-editors-choose-image-variants.md).

You can browse the complete showcase implementation in the [ResponsiveImages folder of the finished branch](https://github.com/Kentico/xperience-by-kentico-training-guides/tree/finished/src/TrainingGuides.Web/Features/ResponsiveImages) and its unit tests in the [ResponsiveImages folder of the test project](https://github.com/Kentico/xperience-by-kentico-training-guides/tree/finished/src/TrainingGuides.Web.Tests/Features/ResponsiveImages). For a complete list of attributes supported by the built-in image tag helpers, see the [tag helper reference](https://docs.kentico.com/documentation/developers-and-admins/development/reference-tag-helpers.md).
