Dynamically override Bootstrap CSS variables in React? - css

So what I have is a React project with Bootstrap.css loaded. I'd like to somehow override the variables, so for instance I have a bunch of buttons like
<button className="btn btn-primary">Hello</button>
Which basically 'inherit' the color from:
:root {
--primary: somecolor;
}
Is there a way to somehow override this? I've tried passing it in as inline style to components, like <Component style={{"--primary" : "red"}} /> which will override the :root { --primary }, but the button colors will remain the same. What's the easiest way to do this, considering I'm supporting dynamic colors, so I can't create a few CSS files, and it would be good if I didn't have to rewrite every single button I have to be a styled-component that minds props!

There's not really an easy way to do this. You could generate the CSS for the "custom" primary colors in SASS, and then add a "root" primary color class to the component like this...
SASS to generate "primary" color Bootstrap CSS
/* import the necessary Bootstrap files */
#import "bootstrap";
#mixin build-primary-classes($color) {
/* background classes */
#include bg-variant(".bg-primary", $color);
/* btn classes */
.btn-primary {
#include button-variant($color, $color);
}
.btn-outline-primary {
#include button-outline-variant($color);
}
/* text- classes */
#include text-emphasis-variant(".text-primary", $color);
/* badge classes */
.badge-primary {
#include badge-variant($color);
}
/* borders */
.border-primary {
border-color: $color !important;
}
}
$customprimarycolors: (
"purple": purple,
"red": red,
"orange": orange
);
#each $colorName, $color in $customprimarycolors {
.#{$colorName} {
#include build-primary-classes($color);
}
}
JS
class Hello extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<div className={this.props.className}>Hello <button className="btn btn-primary">Button</button></div>
);
}
}
ReactDOM.render(<Hello className="red" />, document.getElementById('root'));
Codeply demo: https://codeply.com/go/R4X5x8taiH

Not sure if this will work, but an idea...
Could you edit your bootstrap.css file like this
:root { --primary: unset; }
That way you wouldn't have to overwrite any bootstrap styles?

HONESTLY ... I am not sure if it is a good idea to try to overwrite in CSS a few part of the classes bootstrap builds on a color var like $primary but let's the rest of the classes build on the same var as it is.
That's the way trouble raises up ...
An IMHO better way would be to do it the way Bootstrap provides it:
Changing in SASS the basic var $primary to the new wanted color in Bootstrap the color will change and the classes are there. Or adding a new color $additional-color and adding the color to map $theme-color and all the additional classes are build up on the fly ... Just have a look to the docs ... it is much more easier than it seems to be on the first look:
https://getbootstrap.com/docs/5.0/customize/color/
So yes: in SASS theming is possible just setting/adding the color vars.
But if in a project it is not possible to use SASS or the direct setup is not wanted for some reasons ... there are many free easy to use theming tools in the web which do the job for you. Than you are able to import a clean and consistend Bootstrap CSS with your wanted colors. Because that it is as easy Bootstrap is as successful (what not means I/you need to like it). As Bootstrap 5 still is Beta here an example for BS4 ...
http://pikock.github.io/bootstrap-magic/app/index.html#!/editor
NOTE: only changing/overwriting the CSS color vars in CSS file is not enough as the colors in the classes are hard coded to the original hex colors. You indeed would have to overwrite the original classes which leads to doubled code structures.

Related

NextJS: Modify third-party component CSS in different pages

With third-party components, the way to include their styles is by importing their stylesheet into _app.tsx or importing the stylesheet into your component that uses the third-party component, as described here: https://nextjs.org/docs/basic-features/built-in-css-support#import-styles-from-node_modules or by adding to next.config.js like so:
// next.config.js
const withTM = require("next-transpile-modules")([
"#fullcalendar/common",
"#fullcalendar/daygrid",
"#fullcalendar/timegrid",
"#fullcalendar/interaction",
"#fullcalendar/react",
"#fullcalendar/list",
To modify the third-party stylesheet, you need to create your own stylesheet and add it to _app.tsx; those modifications might look like this:
// styles/modified-fullcalendar.scss
.fc-col-header {
width: 100% !important;
}
Another option, at least for my use case (Full Calendar) is to use CSS variables as described here in technique 2 on this page: https://fullcalendar.io/docs/css-customization. There was a lengthy thread about this on the Full Calendar issues page, as seen here: https://github.com/fullcalendar/fullcalendar/issues/5393
The problem with all of these methods of customization is that they're global, and so anywhere you use this third-party component it'll look the same. However, in my case, I want to use the component on two different pages, with different styling modifications. With most frameworks, I would simply import the relevant modified stylesheet wherever I needed it, but NextJS doesn't allow that. How can I achieve the modifications I want?
The solution is to wrap the component in a div with a specific class name, then do the css overrides in a nested format for each use case in the override file.
Explanation:
Say your third-party component is FullCalendar. It's being imported and used in the files Foo.tsx and Bar.tsx. In Foo, let's say you want the calendar cells to be green.
To make the modification, you create the file modified-fc.scss and do the following:
// modified-fc.scss
.fc-cell {
background: green !important;
}
You then import modified-fc.scss into _app.tsx in order to apply the styles globally, and you're done. However, this prevents you from changing the cell color to orange in Bar. To circumvent this, just wrap the component:
// Foo.tsx
<div className=".wrapper1">
<FullCalendar/>
</div>
// Bar.tsx
<div className=".wrapper2">
<FullCalendar/>
</div>
and then nest the classes:
// modified-fc.scss
.wrapper1 {
.fc-cell {
background: green !important;
}
}
.wrapper2 {
.fc-cell {
background: orange !important;
}
}
OR
.wrapper1 > .fc-cell {
background: green !important;
}
.wrapper2 > .fc-cell {
background: orange !important;
}

Change default color of Bootstrap btn-primary class

I know I can simply do this in my SCSS file. But I would like to know the correct way to do it via customizing the actual Bootstrap colors. I have already figured out how to change background colors on the buttons.
I created a custom-bootstrap.scss file in which I modified the $primary and $danger variables and then imported Bootstrap.
custom-bootstrap.scss:
// Override default variables before the import
$primary: #48BF91;
$danger: #CF6676;
// Import Bootstrap and its default variables
#import '~bootstrap/scss/bootstrap.scss';
This is my inspector showing where it sets the text color to black from the _buttons.scss file.
Edit: So right now, this is how I am currently changing the button text color. Just by adding this code into my own SCSS file. But it feels too hacky for me, I want to modify the Bootstrap variables.
.btn-primary {
color: $text;
&:hover {
color: $text;
}
}
use this type
:root {--button-color: black; --button-background-color: silver;}

What is best fit to use for theming variables or mixins in sass

I am creating a UI library in which I want to provide the mechanism to theme all the UI components like button, cards, slider and all. I am confused between variables and mixins.
One way is to provide the no. of variables that user can update and based on that variables component classes will be derived. The same concept is used in the materialzecss library. And user will use like
//variables that are used to create component css classes
$primary : "blue";
$btn-primary :"green";
//then include the ui library
#import "_ui-variables";
#import "ui-library";
_ui-variables.scss
$primary : "red" !default;
$btn-primary: $primary !default;
// and other variables
and the _btn.scss will be like
.btn {
// other rule sets
color:$btn-primary;
}
Other way could be to use mixins. There will be a theme file for every component that will contain the theme mixin for that component and at the library level, there will be theme mixin that will include all the mixin of the individual component. As the angular-material has done
_btn.scss
#import "_btn-theme.scss";
.btn {
// some rules
}
_btn-theme.scss
#mixin btn-theme($theme) {
// if user has added the btn-primary then use btn-primary otherwise primary
#if map-has-key($theme,btn-primary) {
$btn-primary : map-get($theme,primary);
} #else {
$btn-primary : map-get($theme,primary);
}
.btn {
color:$btn-primary;
}
}
and the ui-library.scss
#import "_btn.scss";
#import "_card.scss";
#mixin ui-theme($theme) {
#include btn-theme($theme);
#include card-theme($theme); // include all component theme
}
and the consumer will call this as
consumer-theme.scss
#import "ui-library";
$theme :(primary:"blue",accent:"yellow");
#include ui-theme($theme);
What are the pros and cons of these approaches? Is there any other way to do this?
If you can use CSS custom properties (CSS variables) that would be really easy. You would just need to add a class to the body change your all your variables at once. So you just need a default theme and then just some classes changing your theme.
I have a small example in one of my project, if you click on "invert theme" it will change the page theme to invert: https://vinceumo.github.io/atomic-bulldog-style-guide-demo/styleguide/section-organisms.html#kssref-organisms-accessibility-settings
The issue with CSS custom properties is that not every brother support it yet :/
https://caniuse.com/#feat=css-variables
Otherwise, I would highly recommend using sass maps. It is easier to maintain when you have few themes, and you can quickly generate your components using #each loop
For example, if you want to generate background color classes:
$color-themes: (
primary:
(
base: #4c5c8c,
dark: darken(#4c5c8c, 15%),
light: lighten(#4c5c8c, 15%),
transparent: transparentize(#4c5c8c, 0.5),
contrast: #ffffff
),
secondary:
(
base: #212529,
dark: darken(#212529, 15%),
light: lighten(#212529, 15%),
transparent: transparentize(#212529, 0.5),
contrast: #ffffff
)
}
#each $name, $theme in $color-themes {
.has-bg-#{$name} {
background-color: map-get($name, base);
color: map-get($name, contrast);
}
}
So here we will get two new classes .has-bg-primary, .has-bg-secondary
If you add new entries to your map it will automatically generate new classes :)
I have created a Scss boilerplate using CSS custom properties (This one can be disabled) with Sass variables. It is optimized for themes creation. Most components are linked to variables (using map). Check it out https://github.com/vinceumo/atomic-bulldog
Variables are going to be your initial best bet.
Creating a theme story isn't something you should rush through, but rather take the time to integrate solid, well thought variables for a base set of colors. After that, you can extend them with things like lighten(), darken(), and other tools built into SASS.
Then, use that base set of variables to establish component specific variables to scale the theme story as needed.

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;
}

Overriding Sass mixin in view template dynamically

I've defined a Sass mixin and used it in a class styling. I'm using the class in template. I need to decide the color on runtime. So I'm trying to override mixin. But its showing in #ff0000 the color I defined in mixin initially.
For some reason I can't use an extra class, What could be the best solution in this scenerio.
My stylesheet app.scss
#mixin mx-color {
color: #ff0000;
}
.my-color {
#include mx-color;
}
Angular template view app.html.haml
:css
#mixin mx-color {
color: {{custom_color}}; // custom_color contains hex-color to replace
}
%body
%p.my-color
This text must show-up in custom color but its showing the default color.
Please check the compiled HTML/CSS output. I don’t think it is possible to just overwrite a mixin and expect the SASS blocks where the mixin was used to update automatically.

Resources