I tried to search, but turns out searching for "css variables" or even "custom properties" isn't particularly helpful. In any case I did go through a bunch of issues and didn't see this mentioned. Thus:
Background: situations where adding Sass to the build pipeline is not feasible or not wanted, but one still wants to use Bootstrap values (e.g. colours, sizes, timings) in custom CSS.
Proposal: to add a :root {} section in the _default_ generated CSS that writes out something like:
:root {
--blue: $blue;
--indigo: $indigo;
--purple: $purple;
--pink: $pink;
/* etc */
}
Usage would then look like:
.custom-component {
box-shadow: var(--dark-gray);
color: var(--indigo);
}
That would either be directly supported by browsers (except IE, Edge, some mobile browsers) or more likely right now compiled-in by the build tool (e.g. PostCSS plugin postcss-custom-properties). Because this is supported right now in modern / dev-used browsers, it also brings a newish component to live editing via the Inspector.
Compatibility: in the event that someone is already using custom properties named the same as the bootstrap variables, then this would only affect them if the bootstrap ones come _after_ their own (otherwise the cascade would take care of it). Apart from that, I don't see any other compatibility problems, but I might have overlooked some.
Interesting idea! Could be cool to do.
Doing something like this:
:root {
@each $color, $value in $theme-colors {
--#{$color}: $value;
}
}
Could output this:
:root {
--primary: #007bff;
--secondary: #868e96;
--success: #28a745;
--info: #17a2b8;
--warning: #ffc107;
--danger: #dc3545;
--light: #f8f9fa;
--dark: #343a40;
}
Tried a PR over at #23446.
I was thinking about this and I believe a good minimal base could be:
$theme-colors as in the PR$colors to have the full bootstrap-picked palette$grid-breakpoints to use in media queries$font-family-* stacksThe many other variables could also be exposed as an option, but looking through the entire list I haven't found any that would be as useful as those ones, especially since a lot of them are derived from base ones, and as this is primarily for default builds, most others (spacers, paragraph margins, number of columns, etc) don't really tip the crud/useful balance imo.
The only one I considered but wasn't sure enough about to include above was $container-max-widths… however I think these can be derived easily enough from the breakpoints.
I'll put together a PR for the above set.
Finally got time to do this. Here's a new PR: #23761
Fixed by #23761.
Could you use this to dynamically change the primary and secondary colours using JavaScript? Something like this:
document.documentElement.style.setProperty('--primary', 'purple');
As far as I can see, the variables are not used anywhere.
These are strictly read-only variables for now. They can be used to use the colours in CSS elsewhere, but not to change the colours in Bootstrap.
Most helpful comment
Tried a PR over at #23446.