I have a custom sass setup with bootstrap 5 and bunch of my own SCSS files, all of this gets compiled in style.css using gulp. I have a _colors.scss file which stores all the colors according to our design language. We use this to generate a bunch of classes that can be used any where to change colors:
// Text Colors
$colors: (
"icon-color": $slate-500,
'slate-10': $slate-10,
'slate-40': $slate-40,
'slate-300': $slate-300,
"secondary": $secondary-text-color,
"green": $green,
"light-green": $green-color,
"blue": $blue,
"blue-200": $blue-200,
"blue-300": $blue-300,
"blue-400": $blue-400,
"dodger-blue": $dodger-blue,
"mariner-blue": $mariner-blue,
"light-blue": $blue-100,
"cadet-blue" : $cadet-blue,
"aqua-10": $aqua-10,
"gray": $gray,
"gray-light": $gray-light,
"light-gray": $gray-100,
"bright-gray": $bright-gray,
"gray-200": $gray-200,
"clay": $clay,
"clay-10": $clay-10,
"mandy-pink": $mandy-pink,
"aqua": $aqua,
"violet": $violet,
"white": $white,
"primary": $primary-text-color
);
#each $color-name, $color-value in $colors {
.text-#{$color-name} {
color: $color-value !important;
}
.bg-#{$color-name} {
background-color: $color-value !important;
}
.border-#{$color-name} {
border-color: $color-value !important;
}
}
Problem is certain classes like .text-gray or .text-blue are not working. My guess is that since bootstrap also uses variables called gray and blue, its conflicting with my variables in _colors.scss.
On closer look, the css does gets generated properly (I found below declaration in final style.css):
.case-study .case-study-right .card .data-bar p:last-of-type,.share .social-media>span,.text-color-gray-200,.text-gray-200 {
color: #69727A!important
}
But using .text-gray has no effect, the class is not getting applied.
How do I fix this? please help!
First, if you're sure that you see the correct selector and the correct rule in your CSS file: it should be applied. And so, the rule should be visible in the browser console (even if overridden).
If you see it in your CSS file, but not applied in the browser console: check that your CSS file is valid (and that your gulp production script compiles fine), as a bad character could mess some part of it.
If you see your CSS in the browser console, but it's overridden by some bootstrap rules, you can override bootsrap variables, and change bootstrap colors by yours like so (import bootstrap before this):
$theme-colors: (
primary: #121212,
success: #8bcea8
...
);
You could also try this to replace bootstrap values by yours:
$theme-colors: map-merge($theme-colors, $colors);
The simple answer is:
Use Bootstrap 5 the intended way!
Bootstrap is a complex framework. All that huge number of classes work together including overwriting color settings if provided and used the intended way. In your code example you additional create helper classes Bootstrap would provide to you out of the box if you use it the Bootstrap way. As you did not do it leads to conflicts which are not easy to handle ... and nearly impossible to solve without to have the possibility to analyize the page itself.
This is what you may check:
You may check: are there other classes which blocks your classes?
In your example you use !important to get higher specifity. But the color is overwritten by other classes ...
Maybe that are Bootstrap which uses !important as well. In that case you can try to add your classes at the end of your CSS (after the Bootstrap classes) so they are able to overwrite in case of identical specifity.
Additional: in your example you added a huge bunch of non-bootstrap-classes. Maybe this individual added classes blocks your styling by adding a color with higher specifity (using !important as well which is not a good technique at all) to your element than your added class do.
In that case same solution may be possible ... but individual classes with !important and an additional higher specifity (i.e. using two class names in the selector) will win over your helper classes also your helper class comes later in your CSS file.
To be honest: most often analyzing such an huddle of classes indeed is only possible in the browser on the page direct using the developer tools.
But best way indeed would be ...
Do a correct Bootstrap theming and use Bootstrap classes!!!
You really don't need to create the helper classes on your own. Just do a SASS setup of Bootstrap ... and add your needed/additional colors NOT (or not only) to map $colors but AS WELL TO Bootstrap map $theme-colors. Bootstrap builds up helper-/utility-/elements-color-classes not on $colors but on $theme-colors. That means: doing that this intended way ... all your helper classes you added in your project on your own will be provided by Bootstrap mechanic in the correct order and avoiding conflicts to your CSS.
Use Bootstrap classes to style your page. Now you don't need to create an additional class .case-study { color: gray }. Just use the Bootstrap helper class and add .text-gray to same element. (Note: In your example you use the incredible number of NINE classes to do the same styling. In case 'text in cards' here is a nice hint how to realize it the bootstrap way: https://getbootstrap.com/docs/5.0/components/card/#border).
Just thinking about using complex Framework...
Bootstrap is done to help you. As there is a lot of code using that Framework only makes sense to use the code as much as possible without writing new classes. So best way indeed to work with it is to use the Bootstrap elements and styling them the Bootstrap way. That makes it simple and avoids conflicts... And: you are able to do nearly everything with these elements.
And if you need to extend Bootstrap i.e. with additonal classes: avoid (deep) nested classes and !important as well so you are able to overwrite settings with simple helper classes.
i had the similar problem it was my scss was successfully converted to the css but not applied, after checking for hours i found out ,i have written B capital while the class name was btn
so when everything is working then the problem is always in your code syntax!
In my project, I use CSS Modules with Less, which means I get the best of both worlds.
My src folder looks something like this:
components/
[all components]
theme/
themes/
lightTheme.less
darkTheme.less
palette.less
palette.less:
#import './themes/lightTheme.less';
Then, in every component that wants to use colors from the theme, I do:
component.module.less:
#import '../../theme/palette.less';
.element {
background-color: #primary;
}
This structure lets me edit palette.less to import the theme I want to use. The thing is that I want to let the users choose their preferred theme on their own. Themes should be switchable on runtime, which means I somehow need to have both themes compiled.
I imagine the perfect solution to be something like this:
app.less
body {
#theme: #light-theme;
&.dark-theme {
#theme: #dark-theme;
}
}
And then somehow import this #theme variable in every component and read properties from it (i.e. #theme[primary]).
Unfortunately, Less variables scoping don't work like this.
I am open-minded to any solution that uses Less modules.
Thank you!
I know that you've probably looking for a solution that uses Less / CSS modules, but it's very likely that your situation can be solved solely with the use of css variables (as Morpheus commented on your question).
How it would work?
You'd have to ensure all your styling does not use hardcoded values, i.e. instead of:
.awesome-div {
background-color: #fefefe;
}
You would have:
:root {
--awesome-color: #fefefe;
}
.awesome-div {
background-color: var(--awesome-color);
}
Changing between light and dark
There are two ways of changing themes in this approach:
Use vanilla Js code within React to update the :root CSS element, check this codepen for more information;
Just load a component containing all new :root variables in its component.css file;
In React (in vanilla CSS too) you can easily have multiple components/elements declaring their own :root at their .css files.
Furthermore, any new :root will overwrite conflicting values from previous :root. For example if at file app.css we have :root { --color: red; } and, when loading another component, component A for instance, where in component_a.css we have the same variable overwritten, e.g. :root { --color: blue; } the one rendered in our browsers will be the one from component A.
Following this logic, you can have a dummy component that does and renders exactly nothing, but instead in this component.js file you import the .css of a theme, e.g.:
import './light.css'; // suppose this is the light-theme dummy component
When switching themes in your app you'd just have to remove the dummy component from scene and call the other one.
I'm not too experienced with codepen to the point of providing you an example containing imports/modules over there, but I hope the above explanation can give you an idea of what I mean. Still, here's a brief pseudo-code of what I'm intending to demonstrate:
loadTheme() {
if (this.state.theme === 'dark') return <LightTheme />;
if (this.state.theme === 'user-3232') return <UserTheme />;
return <DarkTheme />;
}
render() {
return (
<App>
{this.loadTheme()}
<OtherContent>
</App>
);
}
Check out Styled components, it can do that.
https://www.npmjs.com/package/styled-components
https://styled-components.com/docs/advanced#theming
I did it myself as a Easter Egg in an app of mine, so I know for sure it works. Unfortunately it is closed so I can't show you the code publicly.
Alrighty, so I am trying to add classes to my page via css. Below is an example of the less.css file I am writing:
.someClass {
.col-sm-6;
}
I swear this worked before, but for whatever reason, my compiler throws an error:
".col-sm-6 is undefined"
Compiler: WinLess
Essentially I'm just trying to assign the col-sm-6 class to a div for width/float etc... Please let me know if you can think of any reasons this wouldn't work.
Thanks!
Bootstrap 3 makes these class names via a dynamic mixin, so they are not directly accessible as mixins themselves (dynamically generated class names are not currently able in LESS to be accessed as mixins). Instead, you need to call the mixin to generate the code by doing this:
.someClass {
.make-sm-column(6);
}
We have many images which are actually picked up based on a color theme (e.g. blue, red, gray ...). We create files with a common name under each theme (e.g. background, ...), is there a way to define the color theme in a common place so that the definition can be abstracted out. This would prevent me from changing the color theme all over the css file.
body {
background: url('../img/blue/background.png');
font-size: 13px;
margin: 0px;
}
While the options suggested here are viable approaches, I'd like to mention SASS and LESS
They are two CSS extension languages, which amongst other things provide variables for doing this sort of color stuff you mention.
You can create dynamical CSS file by using any serverside scripting language like PHP.
style.css.php:
<?php
header("Content-type: text/css");
$theme = 'blue';
$color1 = '#fefefe';
?>
body {
background: url('../img/<?=$theme?>/background.png');
font-size: 13px;
margin: 0px;
}
.sometext {
color: <?=$color1?>
}
I don't believe you can with a pure css implementation as you would need to define your base paths for your images in a variable which you set with some logic (switch statement, if/else if, ..etc.) and then use that variable in the css.
Here are some options I thought of to do this. If you create a pseudo css file with your variable defined as a string that does not occur in css (ex: $basePath) and build out all your css rules in this fake css file as "$basePath+image.jpg". Then with some server side code retrieve the css file and create your template css files by replacing $basePath+ with the actual base path for that theme. The server side code would then save those css files as theme1.css, theme2.css, ...etc.
You then could use url variables to switch between themes using some server side code to insert a reference to the correct css theme file.
This way you would only need to maintain your pseudo template css file. Although you would need to rerun your css creation code each time you change the template css file so that your theme css files get updated.
Not natively in CSS - but you can write some scripts to compile your theme CSS files from templates with variable substitution. I would suggest having a 'layout' and a 'colour' css. The layout would be consistent irrespective of which theme the user is using. The colour css contains only those settings that change per theme.
<style type="text/css">
#import ulr(layout.css);
#import ulr(theme_<?= $activeTheme ?>_.css);
</style>
You could use a tool such as http://lesscss.org/ (if you like Ruby) to create your themed CSS files.
We use NAnt for something similar to this (not CSS, but same idea), and it saves a heap of time rather than maintaining multiple files that differ only by values.
I’m working on a CSS file that is quite long. I know that the client could ask for changes to the color scheme, and was wondering: is it possible to assign colors to variables, so that I can just change a variable to have the new color applied to all elements that use it?
Please note that I can’t use PHP to dynamically change the CSS file.
CSS supports this natively with CSS Variables.
Example CSS file
:root {
--main-color:#06c;
}
#foo {
color: var(--main-color);
}
For a working example, please see this JSFiddle (the example shows one of the CSS selectors in the fiddle has the color hard coded to blue, the other CSS selector uses CSS variables, both original and current syntax, to set the color to blue).
Manipulating a CSS variable in JavaScript/client side
document.body.style.setProperty('--main-color',"#6c0")
Support is in all the modern browsers
Firefox 31+, Chrome 49+, Safari 9.1+, Microsoft Edge 15+ and Opera 36+ ship with native support for CSS variables.
People keep upvoting my answer, but it's a terrible solution compared to the joy of sass or less, particularly given the number of easy to use gui's for both these days. If you have any sense ignore everything I suggest below.
You could put a comment in the css before each colour in order to serve as a sort of variable, which you can change the value of using find/replace, so...
At the top of the css file
/********************* Colour reference chart****************
*************************** comment ********* colour ********
box background colour bbg #567890
box border colour bb #abcdef
box text colour bt #123456
*/
Later in the CSS file
.contentBox {background: /*bbg*/#567890; border: 2px solid /*bb*/#abcdef; color:/*bt*/#123456}
Then to, for example, change the colour scheme for the box text you do a find/replace on
/*bt*/#123456
Yeeeaaahhh.... you can now use var() function in CSS.....
The good news is you can change it using JavaScript access, which will change globally as well...
But how to declare them...
It's quite simple:
For example, you wanna assign a #ff0000 to a var(), just simply assign it in :root, also pay attention to --:
:root {
--red: #ff0000;
}
html, body {
background-color: var(--red);
}
The good things are the browser support is not bad, also don't need to be compiled to be used in the browser like LESS or SASS...
Also, here is a simple JavaScript script, which changes the red value to blue:
const rootEl = document.querySelector(':root');
root.style.setProperty('--red', 'blue');
CSS itself doesn't use variables. However, you can use another language like SASS to define your styling using variables, and automatically produce CSS files, which you can then put up on the web. Note that you would have to re-run the generator every time you made a change to your CSS, but that isn't so hard.
You can try CSS3 variables:
body {
--fontColor: red;
color: var(--fontColor);
}
There's no easy CSS only solution. You could do this:
Find all instances of background-color and color in your CSS file and create a class name for each unique color.
.top-header { color: #fff; }
.content-text { color: #f00; }
.bg-leftnav { background-color: #fff; }
.bg-column { background-color: #f00; }
Next go through every single page on your site where color was involved and add the appropriate classes for both color and background color.
Last, remove any references of colors in your CSS other than your newly created color classes.
The 'Less' Ruby Gem for CSS looks awesome.
http://lesscss.org/
Yes, in near future (i write this in june 2012) you can define native css variables, without using less/sass etc ! The Webkit engine just implemented first css variable rules, so cutting edge versions of Chrome and Safari are already to work with them. See the Official Webkit (Chrome/Safari) development log with a onsite css browser demo.
Hopefully we can expect widespread browser support of native css variables in the next few months.
Do not use css3 variables due to support.
I would do the following if you want a pure css solution.
Use color classes with semenatic names.
.bg-primary { background: #880000; }
.bg-secondary { background: #008800; }
.bg-accent { background: #F5F5F5; }
Separate the structure from the skin (OOCSS)
/* Instead of */
h1 {
font-size: 2rem;
line-height: 1.5rem;
color: #8000;
}
/* use this */
h1 {
font-size: 2rem;
line-height: 1.5rem;
}
.bg-primary {
background: #880000;
}
/* This will allow you to reuse colors in your design */
Put these inside a separate css file to change as needed.
Sure can, sort of, thanks to the wonderful world of multiple classes, can do this:
.red {color:red}
.blackBack {background-color: black}
but I often end up combining them anyway like this:
.highlight {color:red, background-color: black}
I know the semantic police will be all over you, but it works.
I'm not clear on why you can't use PHP. You could then simply add and use variables as you wish, save the file as a PHP file and link to that .php file as the style sheet instead of the .css file.
It doesn't have to be PHP, but you get what I mean.
When we want programming stuff, why not use a programming language until CSS (maybe) supports things like variables?
Also, check out Nicole Sullivan's Object-oriented CSS.
You can group selectors:
#selector1, #selector2, #selector3 { color: black; }
You could pass the CSS through javascript and replace all instances of COLOUR1 with a certain color (basically regex it) and provide a backup stylesheet incase the end user has JS turned off
dicejs.com (formally cssobjs) is a client-side version of SASS. You can set variables in your CSS (stored in json formatted CSS) and re-use your color variables.
//create the CSS JSON object with variables and styles
var myCSSObjs = {
cssVariables : {
primaryColor:'#FF0000',
padSmall:'5px',
padLarge:'$expr($padSmall * 2)'
}
'body' : {padding:'$padLarge'},
'h1' : {margin:'0', padding:'0 0 $padSmall 0'},
'.pretty' : {padding:'$padSmall', margin:'$padSmall', color:'$primaryColor'}
};
//give your css objects a name and inject them
$.cssObjs('myStyles',myCSSObjs).injectStyles();
And here is a link to a complete downloadable demo which is a little more helpful then their documentation : dicejs demo
EDIT: This answer is no longer current. You should use CSS variables now.
Consider using SCSS. It's full compatible with CSS syntax, so a valid CSS file is also a valid SCSS file. This makes migration easy, just change the suffix. It has numerous enhancements, the most useful being variables and nested selectors.
You need to run it through a pre-processor to convert it to CSS before shipping it to the client.
I've been a hardcore CSS developer for many years now, but since forcing myself to do a project in SCSS, I now won't use anything else.
If you have Ruby on your system you can do this:
http://unixgods.org/~tilo/Ruby/Using_Variables_in_CSS_Files_with_Ruby_on_Rails.html
This was made for Rails, but see below for how to modify it to run it stand alone.
You could use this method independently from Rails, by writing a small Ruby wrapper script
which works in conjunction with site_settings.rb and takes your CSS-paths into account, and
which you can call every time you want to re-generate your CSS (e.g. during site startup)
You can run Ruby on pretty much any operating system, so this should be fairly platform independent.
e.g. wrapper: generate_CSS.rb (run this script whenever you need to generate your CSS)
#/usr/bin/ruby # preferably Ruby 1.9.2 or higher
require './site_settings.rb' # assuming your site_settings file is on the same level
CSS_IN_PATH = File.join( PATH-TO-YOUR-PROJECT, 'css-input-files')
CSS_OUT_PATH = File.join( PATH-TO-YOUR-PROJECT, 'static' , 'stylesheets' )
Site.generate_CSS_files( CSS_IN_PATH , CSS_OUT_PATH )
the generate_CSS_files method in site_settings.rb then needs to be modified like this:
module Site
# ... see above link for complete contents
# Module Method which generates an OUTPUT CSS file *.css for each INPUT CSS file *.css.in we find in our CSS directory
# replacing any mention of Color Constants , e.g. #SomeColor# , with the corresponding color code defined in Site::Color
#
# We will only generate CSS files if they are deleted or the input file is newer / modified
#
def self.generate_CSS_files(input_path = File.join( Rails.root.to_s , 'public' ,'stylesheets') ,
output_path = File.join( Rails.root.to_s , 'public' ,'stylesheets'))
# assuming all your CSS files live under "./public/stylesheets"
Dir.glob( File.join( input_path, '*.css.in') ).each do |filename_in|
filename_out = File.join( output_path , File.basename( filename_in.sub(/.in$/, '') ))
# if the output CSS file doesn't exist, or the the input CSS file is newer than the output CSS file:
if (! File.exists?(filename_out)) || (File.stat( filename_in ).mtime > File.stat( filename_out ).mtime)
# in this case, we'll need to create the output CSS file fresh:
puts " processing #{filename_in}\n --> generating #{filename_out}"
out_file = File.open( filename_out, 'w' )
File.open( filename_in , 'r' ).each do |line|
if line =~ /^\s*\/\*/ || line =~ /^\s+$/ # ignore empty lines, and lines starting with a comment
out_file.print(line)
next
end
while line =~ /#(\w+)#/ do # substitute all the constants in each line
line.sub!( /#\w+#/ , Site::Color.const_get( $1 ) ) # with the color the constant defines
end
out_file.print(line)
end
out_file.close
end # if ..
end
end # def self.generate_CSS_files
end # module Site
Not PHP I'm afraid, but Zope and Plone use something similar to SASS called DTML to achieve this. It's incredibly useful in CMS's.
Upfront Systems has a good example of its use in Plone.
If you write the css file as an xsl template, you could read color values from a simple xml file. Then create the css with an xslt processor.
colors.xml:
<?xml version="1.0"?>
<colors>
<background>#ccc</background>
</colors>
styles.xsl:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" version="1.0" encoding="iso-8859-1"/>
<xsl:template match="/">body {
background-color: <xsl:value-of select="/colors/background" />;
}
</xsl:template>
</xsl:stylesheet>
Command to render css: xsltproc -o styles.css styles.xsl colors.xml
styles.css:
body {
background-color: #ccc;
}
It’s not possible with CSS alone.
You can do it with JavaScript and LESS using less.js, which will render LESS variables into CSS live, but it’s for development only and adds too much overhead for real-life use.
The closest you can come with CSS is to use an attribute substring selector like this:
[id*="colvar-"] {
color: #f0c69b;
}
and set the ids of all your elements that you want to be adjusted to names starting with colvar-, such as colvar-header. Then when you change the color, all the ID styles are updated. That’s as close as you can get with CSS alone.