Blazor: Is it possible to dynamically change the background image of a CSS class in real time?

Setting the background image during design time is straightforward:

.page-background-class {
background-image:url(../images/image-name.png)

}

However, I am interested in dynamically setting the background image at runtime. My goal is to display the image of a logged in user. It would be ideal to use a URL, but an embedded option could also work.

Thanks in advance,

Answer №1

You're heading in the right direction. Forget about Javascript, because you're working with Blazor now. I'm not sure where you plan to use this image, so I can't provide specific guidance. But remember, in Blazor, everything in the UI is a component!

To make it simpler for demonstration purposes, let's set the background color on a component instead of using an image.

Start by creating a new Razor component called MyBackground.razor

<div style="background-color:@this.Color" @attributes="Attributes">
    @ChildContent
</div>

@code {

    [Parameter] public string Color { get; set; }

    [Parameter] public RenderFragment ChildContent { get; set; }

    [Parameter(CaptureUnmatchedValues = true)] public IDictionary<string, object> AdditionalAttributes { get; set; }

    private IDictionary<string, object> Attributes
    {
        get
        {
            var attr = "style";
            if (this.AdditionalAttributes != null)
                if (this.AdditionalAttributes.ContainsKey(attr)) this.AdditionalAttributes.Remove(attr);
            return AdditionalAttributes;
        }
    }
}

You can then utilize this component - I've added it to Index.razor in the standard template

@page "/"

@using TestBlazorServer.Components

<MyBackground Color="@this.color" class="p-5" style="background-color:black">
    <h1 class="border-primary">Hello, world!</h1>

    Welcome to your new app.

    <SurveyPrompt Title="How is Blazor working for you?" />

</MyBackground>

@code{

    private string color { get; set; } = "#bbf";

}

I've included some additional attributes to showcase how they are handled by the component. The class attribute is passed through, while the style attribute is removed, resulting in a blue background instead of black with ample padding.

The basic code structure for your component would resemble:

<div style="background-image:@this.ImageUrl" @attributes="Attributes">
    @ChildContent
// Or HTML code to build out my UserDisplay Component
</div>

@code {

    [Parameter] public string ImageUrl { get; set; }

    [Parameter] public RenderFragment ChildContent { get; set; }

    [Parameter(CaptureUnmatchedValues = true)] public IDictionary<string, object> AdditionalAttributes { get; set; }

    private IDictionary<string, object> Attributes
    {
        get
        {
            var attr = "style";
            if (this.AdditionalAttributes != null)
                if (this.AdditionalAttributes.ContainsKey(attr)) this.AdditionalAttributes.Remove(attr);
            return AdditionalAttributes;
        }
    }
}

Remember to place any specific component CSS in a separate component CSS file. For more information, refer to MS Docs on Component CSS.

Answer №2

To implement a background image using Javascript, include the following line of code:

// Change the URL to your desired image path.
document.querySelector('.page-background-class').style.backgroundImage = 'url("https://example.com/image.jpg")';
.page-background-class {
  width: 100px; 
  height: 100px;
  border: 1px solid #888;
}
<div class="page-background-class"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Disabling the <A> tag within an image due to image map functionality

My thumbnails are set up to be different links, usually accomplished with this code: <a href=#><img src=# /></a> However, I have now converted each thumbnail into an image map (changing the thumbnail as you mouse over). Despite my attem ...

What is the best way to use inline-block for older versions of Internet Explorer, specifically under

Looking to display rating stars in a row using repeated images with the inline-block property: <span class="stars" style="width:20px; margin-top:15px;"> <span style="width:40px;"></span> </span> span.stars, span.stars span { ...

Branding image from Bootstrap overlapped with a container situated below the navigation bar

I'm having trouble adding a 400 x 100 png logo as a Navbar Brand image in Bootstrap 5. The logo is appearing too large, and even when I try to resize it, it still overlaps the black container and text input box below the Navbar in desktop view. On mob ...

Can the vacant space on an HTML page be determined through calculation?

Could someone please help me figure out the amount of empty space on a html page? https://i.sstatic.net/VXzbz.png Is it possible to determine the area highlighted in red using javascript? Apologies if this question seems trivial. ...

Navigating with just a single instance of identical pseudo elements

I am attempting to replicate a design similar to this: https://i.sstatic.net/pJPBj.png In this design, the ribbon in the middle is an image, while the gradients surrounding it are created using CSS. My objective is to have an element act as the title on ...

Guide to adding animation to the Bootstrap 4 Dropmenu

There is a collapse animation on the navbar toggler: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-sca ...

MUI version 5 - Keep styling separate from component files

Seeking to segregate styling from component File in MUI v5. In the past, I accomplished this in v4 by utilizing makeStyles as shown below: Page.style.js: import { makeStyles } from "@material-ui/core"; export const useStyles = makeStyles({ ro ...

What is the best way to customize media queries in a child theme?

Is it possible to override a media query in my Wordpress child theme? Currently, the media query is set at max-width: 1024px, but I would like it to be triggered at a smaller size, maybe around 700px. The issue arises when attempting to create a new media ...

Tips for showing an inline <span> within <div> elements

Is there a way to showcase inline spans within a div element while ensuring they are displayed equally in size and space, based on the user's screen? And how can I ensure that these spans are positioned behind other div elements? body { width: au ...

Tips for applying color to a complete div within a fixed header while positioning the text in the center

I have a header with row elements that are filling it completely using the class "col-xs-2". I am trying to fill the color for one specific "col-xs-2" element and center the text within it. However, the color is only filling the "col-xs-2" div. Can someone ...

What is the best way to adjust the width of a column grid header in extjs

When adjusting the width of a vertical header in a grid to 50px, the header text disappears unless manually dragged to the left. How can I ensure the header text remains visible even with a smaller header size? Consider the following code snippet: { text ...

How to customize a disabled paper-input element in Polymer 1.0?

Help with Polymer 1.0: I've encountered an issue where setting a paper-input element to 'disabled' results in very light gray text and underline, making it hard to read. I've been trying to use CSS to change the text color but haven&ap ...

Broken hyperlinks on images that have been crossfaded are causing issues

I am currently working on a unique design feature that involves 5 crossfading images with hover divs appearing above them. To achieve this effect, I have added link references to each image and set the CSS properties accordingly for smooth animation. In ...

What is causing the discrepancy in height between my parent DIV and its children?

I've been grappling with this issue for quite some time now and unfortunately, I haven't been able to come up with a solution. Within my design, I have a frame that consists of a top box, a left box, a right box, and a middle box that contains th ...

Guide to Presenting HTML data stored in an SQL database on an ASP.NET webform

I need help figuring out how to dynamically display a blog page from my database. The content I'm pulling contains HTML tags, so right now it's showing the raw data with tags included. What I really want is for it to display like a proper page. ...

Is there a way to smoothly incorporate a new animation into a page, while ensuring that existing elements adjust to make room for it?

I am looking to smoothly fade and move a hidden element (display:none) within the page, shifting other elements to animate into their new positions as necessary. When I reveal the hidden element by changing it to "display:initial," it should seamlessly a ...

Steps for adding a border to kendo grid row hover

One of my tasks involved creating a grid using Kendo, and I wanted to display borders on a grid row when the cursor hovers over it. I attempted the following code snippet: .k-grid > table > tbody > tr:hover, .k-grid-content > table > tbody ...

Is it possible to modify the vertical alignment of checkboxes within HTML text?

Currently working on a website using Bootstrap 4. Noticed that, in Chrome on Windows 10, the checkboxes appear slightly higher than usual: https://i.sstatic.net/px6Ns.png These checkboxes are wrapped within <label> tags and created using <input ...

Mystery of the Unresponsive MD Ripple Button

While working on creating a CSS button, I wanted to incorporate the Material Design ripple or wave effect into it. I came across a simple script on codepen that works well by adding the class "ripple" to various elements such as divs, buttons, images, and ...

Choosing particular contenteditable divisions using jQuery

Consider the following HTML structure for a specific type of blog post editor: <div class="entry"> <div class="title" contenteditable="true"> <h2>Title goes here</h2> </div> <div class="content" contenteditable ...