dynamically change colors css - css

I am trying to dynamize color changing in my application built with react and CSS modules. I want to display complementary colors based on one color for each time.
To do that I defined my colors manually
style: [
{
toolbarColor:'#c80eff',
centerWidgetColor:'#0040ff',
buttomWidgetColor:'#0040ff',
rightWidgetColor:'#ffbf00',
},
{
toolbarColor:'#c80eff',
centerWidgetColor:'#fab81e',
buttomWidgetColor:'#00ff9c',
rightWidgetColor:'#12b274',
},...
But it is a long work to do and it is impossible to define all the cases.
For that, my question is, is there any equation to get complementary colors, shades, etc based on one color reference ( hex or rgb )

You can do it in two ways:
CSS
For all CSS, use variables and mixins ( for more information read this article: http://thesassway.com/intermediate/mixins-for-semi-transparent-colors ) but for that code:
$color00: #c80eff;
$color02: #0040ff;
$color03: #00ff9c;
Defining your colors will always create consistency. Then, create a mixin of the like similar to:
```
#mixin alpha-background-color($color, $background) {
$percent: alpha($color01) * 100%;
$opaque: opacify($color, 1);
$solid-color: mix($opaque, $background, $percent);
background-color: $solid-color;
background-color: $color02;
}
```
Finally, you would apply to your item:
```
.button {
#include alpha-background-color(rgba(black, 0.5), white);
}
```
Otherwise, you can do that with JS:
set your variable for the color
$color00: #c80eff;
set a trigger in the button
<button onClick="changeColor()" > Change color </button>
set the function, something on the lines of :
const changeColor = ( opacity) => {
const b = document.querySelector('.button');
let colorChange = b.style.backgroundColor;
// change opacity
b.style.opacity = `${opacity}`;
}
changeColor('set here the opacity you would want');
document.querySelector('.button').addEventListener('click',
changeColor);
Summary and suggestion:
However, any good project will have some defined color palette and styles, if you set those up in variables in CSS then you simply re use them everywhere else in the project. Otherwise it will end up being inconsistent.

Dynamic CSS Background Color
If you're using a framework like Vue and you are receiving your data from a database that contains stuff like the colors etc, you could either have specific classes but that gets tedious...
I recently found that you could pass a css variable to your html as a style property and then use that variable in your css...
Of course, this needs to be edited to change the below red to a variable of your choosing, this is just the concept.
<style>
.myDiv {
height: 200px;
width: 200px;
background: var(--backgroundColor);
}
</style>
<div class="myDiv" style="'--backgroundColor: red;'>Some block</div>
From here, you would use Javascript to either change the value of your css variable with the below
const root = document.querySelector(':root');
root.style.setProperty('--backgroundColor', 'blue');
Or in Vue logic simply dynamically change the value with something like this
<div class="myDiv" :style="'--backgroundColor: ' + backgroundVariable + ';'">
Some Block
</div>

Related

Change color palette depending on variable in SCSS

I have multiple components in my react app using a top navbar, sidebar, cards, etc. All share the same color palette (assets/css/variables.scss):
$nav-color: #009788;
$side-color: #9be7db;
$side-color-selected: #84ebdb;
What I want to do is to change these three colors depending on a variable, for example, a boolean returned by the login. Is this posible to achieve in the variable.scss file?
Obviously, I want to keep the variables names cause all the components use these variables. I only want to change the variables values.
You cannot do it purely with Sass, because sass is pre-rendered to CSS, so any variables are resolved to a value by the time they are delivered to the browser. However, you can point the Sass variables to CSS Custom Properties (Variables) and then update the value of the CSS variables with JS at your whim. Below is an example with CSS only-- but you can point Sass vars at CSS vars.
document.querySelector('#toggleTheme')
.addEventListener('click', () => {
const themeVar = '--theme-color';
const themeColor = document.body.style.getPropertyValue(themeVar);
const newThemeColor = themeColor === 'red' ? 'blue' : 'red';
document.body.style.setProperty(themeVar, newThemeColor);
});
:root {
--theme-color: red;
}
h1 {
color: var(--theme-color);
}
<h1>Hello World</h1>
<button id="toggleTheme">Toggle Theme Color</button>

Vuejs: How to bind a variable to global css class?

I would like to bind a variable as it:
<style lang='sass'>
.picker-item.picker-item-selected
background-color: {{ MY_BG_COLOR }}
</style>
this obviously does not work.
For the context I'm using a picker from framework7 which I want to override the background-color depending of user actions.
Then I cannot really use usual ways to bind values for styling
Is there a way to bind a value for global css class?
You can't do that you want directly, but you can Use "inline style":
You must to bind an inline style with a variable
<div id="app">
<div :style="divInline">Hello</div>
</div>
You must create the variable in the data section
data: {
divInline: 'background-color:red;'
}
after that, you can change the inline style through methods.
methods: {
changeColor( color ) {
this.divInline = 'background-color:' + color + ';'
}
}
Example complete

Angular Material mat-spinner custom color

Does anyone know how can I change mat-spinner color in Angular Material?
Overriding css doesn't work. I tried changing color in material files but they can only be imported, I can't change anything there.
I want it to be my custom color, not color from prebiult-themes.
Use this code for ** < mat-spinner >** add this code in your .css file
.mat-progress-spinner circle, .mat-spinner circle {
stroke: #3fb53f;
}
This answer will work for those who're looking for a flexible solution in Angular 4 / 6 / 7. If you wan't to change the color of a mat-spinner at a component level, you'll need to use the ::ng-deep selector. Knowing this, the solution is quite easy.
In your html file:
<div class="uploader-status">
<mat-spinner></mat-spinner>
</div>
In your css / scss file:
.uploader-status ::ng-deep .mat-progress-spinner circle, .mat-spinner circle {
stroke: #000000;
}
Notice that the .uploader-status css class encapsulates the component. You could just use ::ng-deep without using a class but then whatever changes you're doing to the mat-spinner will appear in other areas of the application. Check this to learn more.
Easy Fix!
Add custom css rules inside styles.css instead of component.css file
.mat-progress-spinner circle, .mat-spinner circle {
stroke: #2A79FF!important;
}
To your .css/.scss component file style add (it will works locally - in component only)
:host ::ng-deep .mat-progress-spinner circle, .mat-spinner circle {
stroke: #bada55;
}
If you don't want to mess around with the global css and need a way to set the spinner to different colors in different areas of your app, I would strongly recommend to create a directive for it.
import { Directive, Input, ElementRef, AfterViewInit } from '#angular/core';
#Directive({
selector: "[customSpinner]"
})
export class CustomSpinnerDirective implements AfterViewInit{
#Input() color: string;
constructor(
private elem: ElementRef
){}
ngAfterViewInit(){
if(!!this.color){
const element = this.elem.nativeElement;
const circle = element.querySelector("circle");
circle.style.stroke = this.color;
}
}
}
Then the spinner should work like this:
<mat-spinner diameter="22" customSpinner color="#fff"></mat-spinner>
mat-spinner html code :
<mat-spinner color="accent" diameter="20" class="loading"></mat-spinner>
And now sass code :
.mat-spinner {
::ng-deep circle {
stroke: #33dd82;
}
}
Color is build in.
Theming
The color of a progress-spinner can be changed by using the color property. By default, progress-spinners use the theme's primary color. This can be changed to 'accent' or 'warn'.
https://material.angular.io/components/progress-spinner/overview
example
<mat-spinner color="warn"></mat-spinner>
I think the key here is that is must be in the GLOBAL styles.css file. The below solution does work if placed there (should be the CSS file affected when material was added to the project if added with ng add:
.mat-progress-spinner circle, .mat-spinner circle {
stroke: #b68200;
}
Of course you could also add classes to the component and specify different selectors if you want distinctly styled spinners. However, it seems the classes must be in the global CSS file.
Late to the game, but this worked well in my .scss file today...
.parent-element-class {
::ng-deep
.mat-progress-spinner,
.mat-spinner {
circle {
stroke: white;
}
}
}
In your styles.css file, add...
::ng-deep .mat-progress-spinner circle, .mat-spinner circle {
stroke: #2A79FF!important;
}
As you might have guessed, I have just made a simple modification to Nitin Wahale's answer. I have prefixed his answer with ::ng-deep and it worked in my case as I had the same issue.
I hope this helps somebody
By default angular material would give your spinner default color of primary.
You can use 3 colors available in pallet that would be primary, accent, warn.
However, if your needs are of different color please consider anyone of the below options.
Easy way(not recommended)
You can use any of method to override css forcefully mention in other answers. I would recommend using parent class above spinner element if you do not want spinner to be of same color throughout the application.
The correct and recommended approach would we to use custom-theme for material. If you already have custom you can just
do like creating a custom mixin called
//here $primary-color is the color you want your spinner to be
#mixin spinner-custom-theme($primary-color, $accent-color, $warn-color) {
$custom-spinner-theme-primary: mat-palette($primary-color);
$custom-spinner-theme-accent: mat-palette($accent-color, A200, A100, A400);
$custom-spinner-theme-warn: mat-palette($warn-color);
$custom-spinner-theme: mat-light-theme($custom-theme-primary, $custom-theme-accent, $custom-theme-warn);
#include mat-progress-spinner-theme($custom-spinner-theme);
}
Now go to file where #include angular-material-theme($custom-theme);
is written
and #include your mixin just below the #include angular-material-theme($custom-theme);
To know more on how to create custom theme you can check this blog here
Sample Color, strokeWidth, diameter and title
<mat-spinner strokeWidth="24" [diameter]="85" color="warn" title="Tooltip text here"></mat-spinner>
In your css file mention like below:
::ng-deep.mat-progress-spinner circle,.mat-spinner circle {stroke: #f2aa4cff !important;}
Here, ::ng-deep will be used to force a style.
!important here what says is that "this is Important",you ignore all other rules and apply this rule.
.mat-mdc-progress-spinner { --mdc-circular-progress-active-indicator-color: white; }
This worked for me using Angular 15.
This is best achieved by doing a custom theme.
https://material.angular.io/guide/theming
use this code
<md-progress-circular md-diameter="20px"></md-progress-circular>
md-progress-circular path {
stroke: purple;
}
In case you guys want to customize each spinner on your webpage. You can do it this way:
svg .mat-progress-spinner circle, .mat-spinner circle {
stroke: inherit;
}
And now on mat-spinner add class:
<mat-spinner class="custom-spinner-color"></mat-spinner>
And in css file:
.custom-spinner-color {
stroke: #234188;
}
That was what I wanted to achieve. I suppose if you look for this question you probably want the same.
Mat progress spinner custom timer, I changed to 3 different colors based on the value passed to mat spinner. Pls refer : https://material.angular.io/components/progress-spinner/examples
<mat-progress-spinner class="mat-spinner" [color]="progressColor"
[diameter]="170" [strokeWidth]="14"[mode]="'determinate'"
[value]="progressLabel">
</mat-progress-spinner>
Ts file
timer: number = TIMER; // say 60 seconds
progressColor: ThemePalette = 'accent';
timerPercent: number = 0;
progressLabel: number = 100;
startTimer() {
this.timer = TIMER;
this.timerInterval = setInterval(() => {
if (this.timer <= 0) {
clearInterval(this.timerInterval);
this.timerFinish();
}
if (this.timer > 0) {
this.progressColor =
this.timerPercent > 69
? 'warn'
: this.timerPercent > 49
? 'primary'
: 'accent';
this.timer--;
this.timerPercent = (100 * (TIMER - this.timer)) / TIMER;
this.progressLabel = 100 - this.timerPercent;
}
}, 1000);
}
For me this is how I do it clean without messing with anything globally:
in my .css
::ng-deep .customColorSpinner circle {stroke: #4e1e1e!important;}
in my .html
<mat-spinner class="customColorSpinner"></mat-spinner>
You can use a custom Angular Directive to solve this problem. The directive allows you to set a custom color on the mat-spinner like this:
<mat-progress-spinner spinnerColor="#09ff00"></mat-progress-spinner>
I have an article here where I explain this and thoroughly show you how to solve it
In component.scss where your mat-spinner exists, just add this :
::ng-deep .mat-mdc-progress-spinner {
--mdc-circular-progress-active-indicator-color: #7D469A;
}

How to dynamically change css selector property value in react js code?

I need to dynamically change the color in the react component for specific selector.
In scss (use sass) i have the following rule:
foo.bar.var * {
color: blue;
}
I want to change it in react code, to be yellow, red or something else.
I cant use style property for element, cause i need the selector to
apply for all subchilds !=)
Is there any native ways? Or should i use Radium? Or is there any similar libs for this? Maybe css-next some hove can help with this?
I have color picker, i cant write class styles for every color =(
For some answerers NOTE:
So i have selector in some scss file, that imported in some root js file with .class * {color: $somecolor} and i need change the $somecolor in that selector, during picking colors in color picker
Maybe i can somehow set selector for all nested inside style property? or there is the way how to recursively apply css style for every nested items from the style prop?
What about
class MyComponent extends React.Component {
render() {
const yellow = true // Your condition
return(
<div className={`foo bar var ${yellow && 'yellow'}`}
My item
</div>
)
}
}
.foo.bar.var {
& * {
color: blue;
}
&.yellow * {
color: yellow;
}
}
You could define a custom CSS property (CSS variables) using the style attribute of the element and assign the value to a prop, state etc.
<div className='foo bar var' style={{ "--my-color": props.color }}></div>
The custom property would work for any selector that apply to that component or children. So you could use it like that:
foo.bar.var * {
color: var(--my-color);
}
See a snippet with similar code here
this may sound stupid . but does this work ?
import myCss from './mydesign.css';
myCss.foo.bar.var = "your color"

User Inputted live Color Scheme Change

I designed a site so that changing two user inputted colors should change the color scheme of the entire site.
What is the best way to accomplish this. I know that I would have to save the items in the database and pull every time the user logged in in order to implement the color scheme with every login.
But at the moment I am more worried about a live change as soon as the user changes the html color value.
I know of an option to where I add a CSS class to every component that would change such as ... .primaryColor and .secondaryColor. And then alter all of the elements with that class. Is there a better way with React or another CSS/Javascript solution?
Also another complication is that it would have to be in a way that when the user loads other components that have not rendered yet, the change is still in affect.
One possible solution is to use the <style> element coupled with dangerouslySetInnerHTML, like this. (Notice the backticks ` around the CSS - it's an interpolated string literal.)
const Theme = props => {
<style dangerouslySetInnerHTML={{__html: `
.styled { color: ${props.userColor} }
`}}
/>
}
Then a component that used the theme would simply be <div className="styled" />
I got the idea for this solution here.
If you use this method, be very careful you're using sanitized variables to create your CSS theme. Otherwise, there's potential problems with injection attacks.
I would use an event listener on the input, read the value, and if it matches whatever you want to trigger the color scheme change, apply the theme value to a data attribute on a root element and use CSS to control the color schemes.
var input = document.getElementById('input'),
body = document.getElementsByTagName('body')[0];
input.addEventListener('keyup',function() {
var val = this.value;
if (this.value == 'foo') {
body.setAttribute('data-theme','secondary');
} else if (this.value == 'bar') {
body.setAttribute('data-theme','primary');
} else {
body.setAttribute('data-theme','');
}
// ajax request to save theme pref in db
})
/* defaults */
body {
color: #333;
}
/* primary theme */
[data-theme="primary"] {
color: red;
}
[data-theme="primary"] p {
background: yellow;
}
/* secondary theme */
[data-theme="secondary"] {
color: blue;
}
[data-theme="secondary"] ul {
background: grey;
}
<input id="input" placeholder="enter 'foo' or 'bar'">
<p>
paragraph
</p>
<ul>
<li>list</li>
</ul>
you can easily do this using js.
just add your class .primaryColor, .secondaryColor with jQuery addClass() Method.
select the element
example :
$(selector).addClass(classname,function(index,currentclass))
more example :https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_addclass

Resources