Skip to content

Utilities

Image

Bit.BlazorUI

An img inside a frame that takes the size and the shape and clips the rest, while ImageFit and ImagePosition place the image in it. It follows the load and error states - covered by a placeholder, templates and a fallback source - and exposes the browser's lazy, priority and responsive loading.

Notes

FadeIn honors the reduced motion preference of the OS/browser (prefers-reduced-motion) and shows the image at once. If nothing on this page fades, turn that setting off, or use the ForceAnimation parameter or the ForceAnimation toggle at the top of this page.

Usage

Every example is live. Open its code to see exactly what produced the component running underneath.

Basic

Src is the file and Alt what it says to anyone who cannot see it. Title is a mouse-only tooltip. A disabled image dims and stops answering the pointer.
The bit platform logo
Disabled
The bit platform logo

Frame size

Width and Height size the frame: a bare number is pixels, anything else any CSS length. One of them scales the image along the other. AspectRatio reserves the frame's room before the image arrives, so nothing below it shifts. Fluid keeps the frame within its container and scales the image down rather than cropping it. The tint behind each image shows its frame.
Width="9rem"
The bit platform logo
Height="80"
The bit platform logo
Width="256px" Height="128px"
The bit platform logo
Width="16rem" AspectRatio="1"
A landscape photograph
Fluid, in a 12rem column
A landscape photograph, scaled down to its column

ImageFit

ImageFit settles an image and a frame of different shapes: None and Center crop it at its natural size, Contain fits it inside, Cover fills the frame and crops, Fill stretches it, and ScaleDown is Contain that never enlarges. CenterContain and CenterCover never enlarge either, and need Cover to say how the two shapes compare: Landscape for an image proportionally wider than its frame (this 2:1 logo in a 5:3 frame), Portrait (the default) for a taller one.
None
The bit platform logo
Center
The bit platform logo
CenterContain
The bit platform logo
CenterCover
The bit platform logo
Contain
The bit platform logo
Cover
The bit platform logo
Fill
The bit platform logo
ScaleDown
The bit platform logo
CenterCover, Landscape (tall frame)
A landscape photograph
CenterCover, Portrait (wide frame)
A landscape photograph

ImagePosition

A fit that crops keeps the middle by default. ImagePosition (CSS object-position) moves the crop to the part that matters.
top
A landscape photograph cropped to its top
center
A landscape photograph cropped to its center
bottom
A landscape photograph cropped to its bottom

MaximizeFrame

MaximizeFrame fills the parent and covers it with the image; an explicit ImageFit still wins.
A landscape photograph
A landscape photograph

Shape & shadow

The frame clips, so Rounded and Circular crop the image. Circular needs a square frame. Bordered and Shadow add the theme's border and card elevation.
Rounded
Circular
Bordered and rounded
Raised and rounded

Loading & error states

The image stays hidden until it loads. LoadingTemplate and ErrorTemplate stand in for it meanwhile, filling a sized frame - here a BitShimmer skeleton holds the image's exact room. OnLoadingStateChange reports each BitImageState, also readable as LoadingState. ReloadAsync fetches the image again, even a source the browser already has.
State: Loading

FallbackSrc

FallbackSrc is tried once when Src fails, and shown at once when there is no Src. Keep it local or inline. An image with nothing to load at all stays in the loading state, since its source may still be on its way, so give one that may have none - an avatar - a FallbackSrc.
A broken Src
The bit platform logo
No Src
The bit platform logo

Progressive loading

FadeIn animates the moment the image appears. StartVisible shows it while it is still drawing and hides it only on failure. PlaceholderSrc - a tiny blurred copy, usually a data URI - fills a sized frame until the image arrives, and cross-fades with it under FadeIn.
FadeIn
An image served with a delay
StartVisible
An image served with a delay
PlaceholderSrc + FadeIn
An image served with a delay

Native loading attributes

Loading, Decoding, FetchPriority, CrossOrigin and ReferrerPolicy are the img attributes of the same names. A Lazy image needs a sized frame and never belongs on the first screen; High priority is for the largest image there. ImageAttributes passes anything else to the img, merged with what the parameters set.
A landscape photograph, loaded lazily
A landscape photograph, fetched first

Responsive sources

Srcset lists the same picture at several widths or densities and Sizes tells the browser how wide it will be laid out, so it fetches no more than it needs. Sources add what a srcset cannot: a different crop per viewport, or a modern format by Type. The first match wins; Src is the answer every browser understands.
Srcset & Sizes
A landscape photograph served at the size the viewport needs
Sources: resize the window across 600px to swap the crop
A landscape photograph, cropped differently on a narrow viewport

OnClick

OnClick makes the image a button: focusable, named by its Alt, activated by Enter and Space as well, and tinted under the pointer - here it opens a larger preview in a BitModal. A disabled one answers neither. Draggable="false" keeps a press from starting a drag.
Preview the photograph
Preview the photograph (disabled)

ChildContent

ChildContent is laid over a sized frame - a caption, a badge, a scrim - and lets clicks through to the image except where the content takes them.
A landscape photograph
A caption laid over the image

Accessibility

The alt is always rendered: leave Alt out for a decorative image, which is then skipped. While the image is hidden - loading, lazily waiting or failed - its alt is still announced. AriaLabel names a clickable image by what it does while the alt describes the picture. FocusAsync focuses a clickable image, which draws the focus ring on the frame.
Decorative
Failed, still announced
Monthly sales chart
AriaLabel
A mountain lake at dawn
Gallery opened 0 times

Cascading parameters

BitParams with a BitImageParams sets defaults for every image under it - the shape, the fit, a FallbackSrc for every broken picture; an image's own value wins (the last one turns rounding off). The source, the alt, the templates and the callbacks are not cascaded.
A landscape photograph
A missing photograph, replaced by the cascaded fallback
A landscape photograph

Style & Class

Style and Class reach the frame; Styles and Classes reach each part: Root, Image, Placeholder, LoadingTemplate, ErrorTemplate and Content. Filters belong on the image, margins on the frame.
Style
The bit platform logo
Class
The bit platform logo
Styles
The bit platform logo
Classes
The bit platform logo

RTL

A picture has no reading direction; Dir changes the flow of what is laid over it and of the templates.
عکسی از یک منظره
نوشته‌ای روی تصویر

CSS variables

The public custom properties this component reads off its root, for what no parameter covers.

Every variable is read with a fallback and never declared by the component, so it inherits like any other custom property: set one on :root (or in a [bit-theme] block) to restyle every instance, on any ancestor to restyle the ones inside it, or on the Style of one instance to restyle that one alone. Leave a variable unset and the component falls back to the theme token beside it.

BitImage CSS variables

Name Default value Description
--bit-Image-background transparent Background of the frame, seen behind a contained image and in a sized frame while the image loads.
--bit-Image-radius --bit-shp-radius-surface Corner radius of a Rounded frame.
--bit-Image-border-width --bit-shp-brd-width Border width of a Bordered frame.
--bit-Image-border-color --bit-clr-brd-sec Border color of a Bordered frame.
--bit-Image-shadow --bit-shd-card Elevation of a Shadow frame.
--bit-Image-hover-shadow --bit-shd-card-hover Elevation of a clickable Shadow frame under the pointer; a press settles it back to --bit-Image-shadow.
--bit-Image-hover-overlay color-mix(in srgb, currentcolor 5%, transparent) Tint laid over a clickable image under the pointer.
--bit-Image-active-overlay color-mix(in srgb, currentcolor 10%, transparent) Tint laid over a clickable image while pressed.
--bit-Image-focus-color --bit-clr-pri-focus Color of the focus ring drawn around the frame of a focused image.
--bit-Image-placeholder-blur 0.5rem Blur radius of the PlaceholderSrc.
--bit-Image-fade-duration --bit-mot-duration-long Pace of the FadeIn. Reduced motion collapses the default (the theme's motion token) unless ForceAnimation is set; a pace set here is the page's own.
--bit-Image-fade-easing --bit-mot-easing Timing function of the FadeIn.

API

Every parameter, public member, sub-class and enum this component exposes.

BitImage parameters

Name Type Default value Description
Alt string? null Specifies an alternate text for the image. The attribute is always rendered, so an image given no text is announced as decorative (alt="") rather than read out as a file name. It is still announced while the image is hidden (loading or failed).
AspectRatio string? null The aspect ratio of the frame of the image, as a CSS aspect-ratio value (e.g. "16/9" or "1"). Reserves the room the image will need before it arrives.
Bordered bool false Renders a border around the frame of the image.
ChildContent RenderFragment? null The content rendered over the image, filling the frame.
Circular bool false Renders the frame of the image as a circle. Takes precedence over Rounded.
Classes BitImageClassStyles? null Custom CSS classes for different parts of the BitImage.
Cover BitImageCover? null How the shape of the image compares to its frame, which the CenterCover and CenterContain fits scale by. No other fit reads it.
CrossOrigin BitImageCrossOrigin? null Specifies the CORS setting the image is requested with.
Decoding BitImageDecoding? null Hints the browser at whether the image may be decoded asynchronously.
Draggable bool? null Specifies whether the image can be dragged by the user.
ErrorTemplate RenderFragment? null The custom template used to show the error state of the image. It fills a sized frame.
FadeIn bool false If true, fades the image in when it becomes visible, cross-fading it with a PlaceholderSrc.
FallbackSrc string? null The source of the image to show when the one given by Src fails to load, or when no Src is given at all. It is tried exactly once.
FetchPriority BitImageFetchPriority? null Hints the browser at the priority this image is fetched with, relative to the other resources of the page.
Fluid bool false Keeps the frame from growing wider than its container, scaling the image down with it rather than cropping it.
Height string? null The image height value. A bare number is read as a pixel count; anything else is used as written.
ImageAttributes Dictionary<string, object> new Dictionary<string, object>() Capture and render additional attributes in addition to the image's parameters. The dictionary is merged with the attributes the component builds itself rather than replaced by them.
ImageFit BitImageFit? null Used to determine how the image is scaled and cropped to fit the frame.
ImagePosition string? null The position of the image inside its frame, as a CSS object-position value (e.g. "top", "50% 25%"). It decides which part of the image survives a crop.
Loading BitImageLoading? null Allows for browser-level image loading (lazy or eager).
LoadingTemplate RenderFragment? null The custom template used to show the loading state of the image. It fills a sized frame, so a skeleton with a 100% height holds the image's exact room.
MaximizeFrame bool false If true, the image frame will expand to fill its parent container.
OnClick EventCallback<MouseEventArgs> null Callback for when the image is clicked. Assigning it makes the image a focusable button that also answers the Enter and Space keys, and tints it under the pointer.
OnError EventCallback null Callback for when the image fails to load, including the failure that is answered by falling back to the FallbackSrc.
OnLoad EventCallback null Callback for when the image has been loaded successfully.
OnLoadingStateChange EventCallback<BitImageState> null Optional callback method for when the image load state has changed.
PlaceholderSrc string? null The source of a placeholder image shown, blurred, while the image itself is still loading.
ReferrerPolicy BitImageReferrerPolicy? null Specifies how much of the address of the current page is sent to whoever serves the image.
Rounded bool false Rounds the corners of the frame of the image.
Shadow bool false Renders a shadow under the frame of the image, lifting it off the surface it sits on. A clickable one lifts further under the pointer.
Sizes string? null The value of the sizes attribute of the image, which tells the browser how wide the image will be laid out at before it knows the layout.
Sources IEnumerable<BitImageSource>? null The alternative sources of the image, offered to the browser ahead of Src. This is the art-direction and the format-negotiation half of responsive images, which Srcset cannot express.
Src string? null Specifies the src of the image. Changing it returns the component to the Loading state.
Srcset string? null The set of image sources the browser may choose from, with their width or density descriptors (e.g. "photo-480.jpg 480w, photo-960.jpg 960w").
StartVisible bool false If true, the image starts as visible and is hidden on error. Otherwise, the image is hidden until it is successfully loaded.
Styles BitImageClassStyles? null Custom CSS styles for different parts of the BitImage.
Title string? null The title to show when the mouse is placed on the image.
Width string? null The image width value. A bare number is read as a pixel count; anything else is used as written.

BitImage public members

Name Type Default value Description
FocusAsync ValueTask Gives the browser focus to the img element of the component. Only a clickable image (one with an OnClick) or one given an explicit TabIndex is focusable at all, so anywhere else the call does nothing.
ImageElement ElementReference The reference to the img element of the component, for whatever has to reach the picture itself rather than the frame around it. RootElement is that frame.
LoadingState BitImageState BitImageState.Loading The current loading state of the image.
ReloadAsync Task Requests the image again from the beginning, whichever state it is in: the component returns to the Loading state, forgets that a FallbackSrc has been tried, and replaces the img element so the browser fetches even a source it already holds an answer for.

BitComponentBase parameters

Name Type Default value Description
AriaLabel string? null Gets or sets the accessible label for the component, used by assistive technologies.
Class string? null Gets or sets the CSS class name(s) to apply to the rendered element.
Dir BitDir? null Gets or sets the text directionality for the component's content.
Disabled bool false Gets or sets a value indicating whether the component is disabled and cannot respond to user interaction.
ForceAnimation bool false Gets or sets a value indicating whether the component's animations play at their full duration even when reduced motion is requested.
HtmlAttributes Dictionary<string, object> new Dictionary<string, object>() Captures additional HTML attributes to be applied to the rendered element, in addition to the component's parameters.
Id string? null Gets or sets the unique identifier for the component's root element.
Style string? null Gets or sets the CSS style string to apply to the rendered element.
TabIndex string? null Gets or sets the tab order index for the component when navigating with the keyboard.
Visibility BitVisibility BitVisibility.Visible Gets or sets the visibility state (visible, hidden, or collapsed) of the component.

BitComponentBase public members

Name Type Default value Description
UniqueId Guid Guid.NewGuid() Gets the readonly unique identifier for the component's root element, assigned when the component instance is constructed.
RootElement ElementReference Gets the reference to the root HTML element associated with this component.

BitImageClassStyles properties

Name Type Default value Description
Root string? null Custom CSS classes/styles for the root element of the image.
Placeholder string? null Custom CSS classes/styles for the placeholder image element, rendered while a PlaceholderSrc is provided and the image itself is not on screen.
Image string? null Custom CSS classes/styles for the image element.
LoadingTemplate string? null Custom CSS classes/styles for the element wrapping the LoadingTemplate of the image.
ErrorTemplate string? null Custom CSS classes/styles for the element wrapping the ErrorTemplate of the image.
Content string? null Custom CSS classes/styles for the overlay element that holds the ChildContent of the image.

BitImageSource properties

One alternative source of the image, rendered as a source element of the picture the image is then wrapped in. The browser walks the sources in order and takes the first one whose Media and Type it is satisfied by.

Name Type Default value Description
Srcset string? null The set of images this source offers, with their width or density descriptors (e.g. "photo-480.avif 480w, photo-960.avif 960w"). This is the only required member.
Media string? null The media query the source applies to (e.g. "(max-width: 600px)"). A source with none applies whatever the viewport is, so it belongs last among the sources that carry one.
Sizes string? null How wide the image will be laid out at, for the browser to choose among a width-descriptor Srcset with.
Type string? null The MIME type of the images this source offers (e.g. "image/avif"). A browser that cannot read the type skips the source without fetching anything.
Width int? null The intrinsic width, in pixels, of the images this source offers.
Height int? null The intrinsic height, in pixels, of the images this source offers.

BitImageFit enum

Name Value Description
None 0 Neither the image nor the frame are scaled. The image keeps its natural size and whatever of it does not fit the frame is cropped away from the right and the bottom.
Center 1 The image is not scaled. The image is centered and cropped within the content box.
CenterContain 2 The image is centered and keeps its aspect ratio: one larger than the frame is scaled down until all of it fits, one smaller keeps its natural size. Scales along the axis Cover names.
CenterCover 3 The image is centered and keeps its aspect ratio: one larger than the frame is scaled down until it just covers it, the overflow cropped; one smaller keeps its natural size. Scales along the axis Cover names.
Contain 4 The image is scaled to maintain its aspect ratio while being fully contained within the frame.
Cover 5 The image is scaled to maintain its aspect ratio while filling the frame.
Fill 6 The image is stretched to fill the frame exactly, without maintaining its aspect ratio.
ScaleDown 7 The image is contained within the frame, but never scaled up: an image smaller than the frame keeps its natural size.

BitImageCover enum

Name Value Description
Landscape 0 The image is proportionally wider than its frame: CenterCover fits its height and crops the sides, CenterContain fits its width.
Portrait 1 The image is proportionally taller than its frame (the default): CenterCover fits its width and crops the top and bottom, CenterContain fits its height.

BitImageState enum

Name Value Description
Loading 0 The image is loading from its source.
Loaded 1 The image has been loaded successfully.
Error 2 An error has been encountered while loading the image. Where a FallbackSrc is provided, this state is only reached once that one has failed as well.

BitImageLoading enum

Name Value Description
Eager 0 Tells the browser to load the image as soon as the img element is processed, which is what a browser does with an img that has no loading attribute.
Lazy 1 Tells the user agent to hold off on loading the image until the browser estimates that it will be needed imminently.

BitImageDecoding enum

Name Value Description
Auto 0 The default behavior, which leaves the decision to the browser.
Sync 1 Decodes the image synchronously, so it is presented together with the rest of the content rendered in the same frame.
Async 2 Decodes the image asynchronously, so the rest of the content is not held back while the decoding runs.

BitImageFetchPriority enum

Name Value Description
Auto 0 The default behavior, which leaves the priority to the browser's own heuristics.
High 1 Fetches the image ahead of the other images of the page, for the one that is the page's largest contentful paint.
Low 2 Fetches the image after the other images of the page, for the ones that carry no meaning on the first screen.

BitImageCrossOrigin enum

Name Value Description
Anonymous 0 Sends a cross-origin request with no credentials: no cookie, no client certificate and no HTTP authentication.
UseCredentials 1 Sends a cross-origin request with credentials. The other origin has to answer with the matching Access-Control-Allow-Credentials header.

BitImageReferrerPolicy enum

Name Value Description
NoReferrer 0 Sends no Referer header at all.
NoReferrerWhenDowngrade 1 Sends the full URL, except to a less secure destination (HTTPS to HTTP), where nothing is sent.
Origin 2 Sends only the origin - the scheme, the host and the port - of the current page.
OriginWhenCrossOrigin 3 Sends the full URL to the same origin, and only the origin to any other one.
SameOrigin 4 Sends the full URL to the same origin, and nothing at all to any other one.
StrictOrigin 5 Sends only the origin, and nothing to a less secure destination (HTTPS to HTTP).
StrictOriginWhenCrossOrigin 6 The default behavior: the full URL to the same origin, the origin alone to another secure one, and nothing to a less secure destination.
UnsafeUrl 7 Sends the full URL to every destination, secure or not.

BitVisibility enum

Name Value Description
Visible 0 The content of the component is visible.
Hidden 1 The content of the component is hidden, but the space it takes on the page remains (visibility:hidden).
Collapsed 2 The component is hidden (display:none).

BitDir enum

Name Value Description
Ltr 0 Ltr (left to right) is to be used for languages that are written from the left to the right (like English).
Rtl 1 Rtl (right to left) is to be used for languages that are written from the right to the left (like Arabic).
Auto 2 Auto lets the user agent decide. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then applies that directionality to the whole element.

Feedback

Found a mistake, a gap, or something that could be clearer? Every page and every component is one click from its source.