Loading
Loading

Reputation: 1110

How to change CSS vars in ASP.NET MVC Core2 dynamically?

I want that the user is able to specify his favorite color. The whole page should then change to this specific color scheme.

My CSS is done with this as base:

:root {
    --maincolor: black;
}

What would be the best way to change this variable inside my CSS dynamically on a button press or something like this?

PS: I would prefer to set this value only a single time and then be done with it

EDIT: Solution for me:

<script>
    var color = "@Html.ViewData["Color"]";
    document.body.style.setProperty('--maincolor', color);
</script>

Was enough to change --maincolor as i want. To set the color put this inside a controller:

ViewData["Color"] = "red"

Upvotes: 0

Views: 2258

Answers (1)

user1477388
user1477388

Reputation: 21430

Your best option, in my opinion, is to associate the user to a CSS class, not a color. Then, changing the class per user becomes trivial.

For example, you could store and retrieve this CSS class from your database or other persistence method. Then, upon retrieval, you could simply add the class to your element via Razor like so:

<div class="@UserColorClassName">
    <p>
        Any text you like here for User: @UserName
    </p>
</div>

There are other variations of this method, as well. For example, you could create a database table of "UserCSSClasses" that would house class names and properties for different users.

Or, you could simply store the CSS hex-color and associate that with the user.

An example of this implementation would be as follows:

<div style="color: @(!string.IsNullOrEmpty(UserHexColor) ? UserHexColor : "")">
    <p>
        Any text you like here for User: @UserName
    </p>
</div>

Edit: It sounds like you have a lot of changes to make on a per-User basis, not just one color. For this, I recommend the following solution:

  1. Store the User/class association in the database or other persistence method as described above.
  2. Instead of applying the class on elements inside of your view, apply it to the body element or that of a containing element.

This way, you can change as many classes as you want with CSS overrides:

body.User001 h1 {
    color: red;
}

body.User001 p {
    color: #c1c1c1;
}

body.User001 p span.caption {
    color: red;
}

body.User002 h1 {
    color: blue;
}

/* etc... */

Upvotes: 1

Related Questions