I’ve got a website that’s using a few different ‘main’ colors. The general HTML layout stays the same, only the colors change depending on the content.
I was wondering if I could set a color variable depending on the CSS selector. This way I can theme my website with a few variables and let Sass fill in the colors.
For example:
$color-1: #444;
$color-2: #555;
$color-3: #666;
$color-4: #777;
body.class-1 {
color-default: $color-1;
color-main: $color-2;
}
body.class-2 {
color-default: $color-3;
color-main: $color-4;
}
/* content CSS */
.content {
background: $color-default;
color: $color-main;
}
I was thinking of using a mixin for this, but I was wondering if there’s a better way to do this—with a function maybe? I’m not that great with Sass, so any help would be appreciated.
I think a mixin is the answer. (As I wrote, variables won’t work.)
#mixin content($color-default, $color-main) {
background: $color-default;
color: $color-main;
}
body.class-1 {
#include content(#444, #555);
}
body.class-2 {
#include content(#666, #777);
}
That SCSS compiles to this CSS:
body.class-1 {
background: #444444;
color: #555555; }
body.class-2 {
background: #666666;
color: #777777; }
If you wanted to group the color values together in your SCSS file, you could use variables in conjunction with the mixin:
$color-1: #444;
$color-2: #555;
$color-3: #666;
$color-4: #777;
body.class-1 {
#include content($color-1, $color-2);
}
body.class-2 {
#include content($color-3, $color-4);
}
as sass documentation explain nicely (https://sass-lang.com/documentation/variables):
Sass variables are all compiled away by Sass. CSS variables are included in the CSS output.
CSS variables can have different values for different elements, but Sass variables only have one value at a time.
Sass variables are imperative, which means if you use a variable and then change its value, the earlier use will stay the same. CSS variables are declarative, which means if you change the value, it’ll affect both earlier uses and later uses.
We may take advantage of that using a combination of sass and css variables to achieve what you want:
//theme colors
$red-cosmo: #e01019;
$green-cosmo: #00c398;
$primary-color: var(--primary-color);
body{
--primary-color: #{$red-cosmo};
}
body.univers-ride{
--primary-color: #{$green-cosmo};
}
So when I call my sass variable $primary-color, it will print as my css variable "var(--primary-color)" that will expand as $green-cosmo only if my body has the "univers-ride" class else it will be $red-cosmo the default color.
If you really want to get hacky you could also define your different color schemes in a single variable like $scheme1: class1 #333 #444, where the first value is always the name, and that is followed by all the colors in that scheme.
You can then use #each:
// Define your schemes with a name and colors
$scheme1: class1 #444 #555;
$scheme2: class2 #666 #777;
$scheme3: class4 #888 #999;
// Here are your color schemes
$schemes: $scheme1 $scheme2 $scheme3;
#each $scheme in $schemes {
// Here are the rules specific to the colors in the theme
body.#{nth($scheme, 1)} .content {
background-color: nth($scheme, 2);
color: nth($scheme, 3);
}
}
This will compile to:
body.class1 .content {
background-color: #444444;
color: #555555; }
body.class2 .content {
background-color: #666666;
color: #777777; }
body.class4 .content {
background-color: #888888;
color: #999999; }
Obviously if you don't want to combine body.class1 and .content in your selectors, you could just specify a mixin content($main, $default) and call it inside the #each using nth just like in the above code, but the point is you don't have to write out a rule for each of your classes.
EDIT There are lots of interesting answers on Creating or referencing variables dynamically in Sass and Merge string and variable to a variable with SASS.
You can also create a mixing that use the ampersand parent selector. http://codepen.io/juhov/pen/gbmbWJ
#mixin color {
body.blue & {
background: blue;
}
body.yellow & {
background: yellow;
}
}
UPDATE: its 2017 and variables does works!
#mixin word_font($page) {
#font-face {
font-family: p#{$page};
src: url('../../static/fonts/ttf/#{$page}.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
.p#{$page} {
font-family: p#{$page};
}
}
// Loop and define css classes
#for $i from 1 through 604 {
#include word_font($i);
}
If you don't want to use a variable for each color, you can use one variable for all kinds of colors. In the mixin you can choose the right color with nth. For instance, if you write the index of the color as 1, then you get the first color in the color variable.
$colors: #444, #555, #666, #777;
#mixin content($color-default-num, $color-main-num) {
background: nth($colors, $color-default-num);
color: nth($colors, $color-main-num);
}
body.class-1 {
#include content(1, 2);
}
For me the definite answer to my problem was creating a map of maps and loopig through them as follows:
$pallettes: (
light-theme: (
container-color: red,
inner-color: blue,
),
dark-theme: (
container-color: black,
inner-color: gray,
),
);
#each $pallette, $content in $pallettes {
.main.#{$pallette} {
background-color: map-get($content, container-color);
.inner-div {
background-color: map-get($content, inner-color);
}
}
}
You can simply override your scss variables inside of the class wrapper:
$color1: red;
$color2: yellow;
header { background: $color1; }
.override-class {
$color1: green;
header { background: $color1; }
}
Seems to work for me.
Related
Is there a neat, simple and beautiful way to implement something like this in scss:
&.red{
--color:red;
}
&.green{
--color:green;
}
&.blue{
--color:blue;
}
&.yellow{
--color:yellow;
}
[...]
background-color:var(--color);
i was thinking something like this:
&.$color{
--color:$color
}
im really new into scss and wanted to know if this is possible in some way.
It sounds like you want to loop through a list of colors to generate new classes, which is definitely doable with proper interpolation:
.button {
$colors: red, green, blue, yellow; // create a list of colors
#each $color in $colors { // loop through each value of a list
&.#{$color} { // need interpolation to use a sass variable in a css selector
--color: #{$color}; // need interpolation for css variable assignment
color: $color; // do not need interpolation for other css properties.
}
}
}
That will output the following compound selectors, based on the $colors list.
.button.red {
--color: red;
color: red;
}
.button.green {
--color: green;
color: green;
}
.button.blue {
--color: blue;
color: blue;
}
.button.yellow {
--color: yellow;
color: yellow;
}
However, since you're already generating classes from a list, I'd suggest creating new class names rather than compound selectors, since these increase specificity. By changing &.#{$color} to &--#{$color} in the loop above, you can get the following BEM-style classes:
.button--red {
--color: red;
color: red;
}
.button--green {
--color: green;
color: green;
}
/* etc. */
I'm looking to support multiple themes in my app - moreover, I want to be able to dynamically change themes, either by changing a class on the body element, or even have different parts of the app use different themes.
In my previous project, I did it by adding explicit rules every time I need to use a theme-specific variable:
.theme-light & { background-color: #theme-light-background; }
.theme-dark & { background-color: #theme-dark-background; }
However, that approach does not scale well and adds unnecessary bloat to source files.
Now, I'm looking for a more automated approach for this. I.e. the following
.button {
border-radius: 4px;
background-color: #ui-background;
color: #ui-foreground;
border: 1px solid mix(#ui-background, #ui-foreground, 50%);
}
would turn into something like
.button {
border-radius: 4px;
border: 1px solid #808080;
/* normally we wouldn't expect this to appear here, but in our case
both themes have the same border color so we can't tell the difference */
}
.theme-light .button {
background-color: #fff;
color: #000;
}
.theme-dark .button {
background-color: #000;
color: #fff;
}
As far as I can tell, neither LESS nor SASS can do this in a natural way. It seems that it wouldn't be too difficult to implement it as a separate post-processor, that builds stylesheets for every theme, then compares them and scopes the differences into the corresponding "namespaces". I suspect that something like this might already exist, but I can't find anything.
Any suggestions?
Not sure about Less, but in Sass it can be implemented relatively easy by storing theme information into maps and using ability to pass content blocks into mixins using #content. Here is example of how it may look like, quite fast solution but you can get an idea:
// Themes definition
// - First level keys are theme names (also used to construct theme class names)
// - Second level keys are theme settings, can be referred as theme(key)
$themes: (
light: (
background: #fff,
foreground: #000,
),
dark: (
background: #000,
foreground: #fff,
),
);
// Internal variable, just ignore
$_current-theme: null;
// Function to refer to theme setting by name
//
// #param string $name Name of the theme setting to use
// #return mixed
#function theme($name) {
#if ($_current-theme == null) {
#error "theme() function should only be used into code that is wrapped by 'theme' mixin";
}
#if (not map-has-key(map-get($themes, $_current-theme), $name)) {
#warn "Unknown theme key '#{$name}' for theme '#{$_current-theme}'";
#return null;
}
#return map-get(map-get($themes, $_current-theme), $name);
}
// Theming application mixin, themable piece of style should be wrapped by call to this mixin
#mixin theme() {
#each $theme in map-keys($themes) {
$_current-theme: $theme !global;
.theme-#{$theme} & {
#content;
}
}
$_current-theme: null !global;
}
.button {
border-radius: 4px;
#include theme() {
background-color: theme(background);
color: theme(foreground);
}
}
This piece of code will give you this result:
.button {
border-radius: 4px;
}
.theme-light .button {
background-color: #fff;
color: #000;
}
.theme-dark .button {
background-color: #000;
color: #fff;
}
Looks pretty close to what you're trying to achieve. You can play with this snippet at Sassmeister.
I want to dynamicaly call .some-mixin() with some colors. This mixins should generate some styles, and when the colors are equals the special code should be generated.
Due to comprimation of final css code I want to do it by help variable, where can I store classes for the special code.
Maybe sample code will be more helpful:
.some-mixin(#newClass,#color,#color2){
.test-mixin(#newClass,#color,#color2);
.#{newClass}{
color: #color;
}
}
#classes: '';
.test-mixin(#newClass,#color,#color2) when (#color = #color2){
#classes: "#{classes}, #{newClass}";
}
.final-mixin(){
.#{classes}{
/*some styles*/
}
}
The call of mixins is generated by PHP and final code should looks like this:
.some-mixin("abc",#ffffff,#000000);
.some-mixin("xyz",#ffffff,#ffffff);
.some-mixin("jkl",#ff00ff,#ff00ff);
.final-mixin();
But when I want compile the LESS it shows infinite loop detected
Is this possible in LESS?
Any advice will be helpul.
As explained in comments, your problem is the recursive variable definition in the below line. Less does not support this as explained in this answer and this one.
#classes: "#{classes}, #{newClass}";
Based on your requirement explanation in comments (that there would be some extra padding etc when the colors are different), you could use one of the below methods.
Option 1: (will add the padding to every class and so repeated code)
.some-mixin(#newClass,#color,#color2){
.#{newClass}{
color: #color;
& when not (#color = #color2){
padding: 4px;
}
}
}
.some-mixin(abc,#ffffff,#000000);
.some-mixin(xyz,#ffffff,#ffffff);
.some-mixin(jkl,#ff00f0,#ff00ff);
The above Less would compile into below CSS:
.abc {
color: #ffffff;
padding: 4px; /* colors were different */
}
.xyz {
color: #ffffff;
}
.jkl {
color: #ff00f0;
padding: 4px; /* colors were different */
}
Option 2: (uses a dummy class + extend and so lesser code)
This option is probably what you are looking for as it avoids code repetition. We cannot extend a mixin and hence we use a dummy class. This should not be a big concern because it just adds one extra line to output CSS.
.common-padding-diff-color{ /* all styles that are needed when colors are different */
padding: 4px;
}
.some-mixin(#newClass,#color,#color2){
.#{newClass}{
color: #color;
& when not (#color = #color2){
&:extend(.common-padding-diff-color);
}
}
}
.some-mixin(abc,#ffffff,#000000);
.some-mixin(xyz,#ffffff,#ffffff);
.some-mixin(jkl,#ff00f0,#ff00ff);
This would compile into
.common-padding-diff-color,
.abc,
.jkl {
padding: 4px; /* style applied for all cases where colors are not same */
}
.abc {
color: #ffffff;
}
.xyz {
color: #ffffff;
}
.jkl {
color: #ff00f0;
}
I'm using LESS as css compiler.
Everything works fine, but now I need to create a specific class structure and I'm a bit stuck.
I'd like to have this structure:
.default .{color} {.icon-after/.icon-before} {.icon}
this is the code that I've done:
.default {
&.disabled {
background: lighten(#grayBackground, 5%);
color: lighten(#darkText, 35%);
cursor: default;
border: #grayBorder;
text-shadow: #grayTextShadow;
}
&.gray {
background: #grayBackground;
color: #darkText;
border: #grayBorder;
text-shadow: #grayTextShadow;
&:hover {
background: darken(#grayBackground, 5%);
}
}
&.green {
background: #greenBackground;
border: #greenBorder;
color: #lightText;
text-shadow: #greenTextShadow;
&:hover {
background: darken(#greenBackground, 10%);
}
}
&.yellow {
background: #yellowBackground;
border: #yellowBorder;
color: #lightText;
text-shadow: #yellowTextShadow;
&:hover {
background: darken(#yellowBackground, 10%);
}
}
&.blue {
background: #blueBackground;
border: #blueBorder;
color: #lightText;
text-shadow: #blueTextShadow;
&:hover {
background: darken(#blueBackground, 10%);
}
}
&.black {
background: #blackBackground;
border: #blackBorder;
color: #lightText;
text-shadow: #blackTextShadow;
&:hover {
background: darken(#blackBackground, 10%);
}
}
&.red {
background: #redBackground;
border: #redBorder;
color: #lightText;
text-shadow: #redTextShadow;
&:hover {
background: darken(#redBackground, 10%);
}
}
&.icon-before{
.IconDefaultStyleBefore
}
&.icon-after{
.IconDefaultStyleAfter()
}
}
obviously this doesn't work, as the result is something like this:
.default .{color / .icon-after / .icon-before}
Any suggestions on how can I obtain my structure?
Thanks a lot
EDIT
I'd like to add the classes to the buttons in this order:
.default( gives the default style )
{.colours} (so that the background, the border and all colour related properties are setted)
{.icon-after or .icon-before} so that I can choose if adding the icon before or after with the proper margin
{.icon-name} (for example a questionmark or a tick etc)
so, for example, adding this classes:
.default .blue .icon-before .tick
I will have:
default blue button with the tick icon before the text
Hope is now more clear than before.
The required structure can be achieved as shown in the below example. The code can be simplified a lot by using loops (guarded mixins).
Explanation:
#colors - An array list variable which has the list of colors required for the element.
#bckground - Another array list variable which holds the required background color for each color class declared in the #colors list.
e(extract(#colors, #index)) and extract(#bckground, #index) - Extract functions are used to fetch the color name and background color value corresponding to the index of each array iteration (similar to colors[i]). e() function is used to extract the color values without the quotes.
&.#{color} - Selector interpolation to form the selector value. & is the parent selector and #{color} is the name of the color from the #colors list variable.
length(#colors) - The no. of color items present in the #colors array list variable. This is passed to the loop function to tell the Less Compiler as to how many times the loop should be executed.
#colors: "red","green","black","blue","gray";
#bckground: #AAA, #0F0, #00F, #000, #F00;
.loop-colors(#index) when (#index > 0){ // loop to generate rules for each color
.loop-colors(#index - 1);// call for the next iteration
#color: e(extract(#colors, #index));
#bgColor: extract(#bckground, #index);
&.#{color}{
background: #bgColor; //set background
/* all other props */
&:hover {
background: darken(#bgColor, 5%);
}
&.icon-before{
.IconDefaultStyleBefore;
}
&.icon-after{
.IconDefaultStyleAfter();
}
}
}
.default{
.loop-colors(length(#colors));
}
Note: As seven-phases-max mentioned in his comment, we are essentially generating a selector structure like .default.red.icon-before. Such a selector would essentially mean the same element has all the three classes and so even if it is specified like .default.icon-before.red it wouldn't make any difference but I assume that you are trying to make a more readable structure (like a default red button with an icon-before).
.default{
[...]
&.gray, &.black, [...every color...] {
.icon-before{
[...]
}
}
}
EDIT: or if you need a different .icon-before for every color you have to insert it one by one:
.default{
[...]
&.gray{
[...]
.icon-before{
[...]
}
}
}
Is there a way to add scope to sass variables?
I want to be able to attach a class to my body element. The class will refer to a set of colours that the rest of the stylesheets can access.
I have tried:
#mixin theme_one{
$color: #000;
}
.theme_one{
#include theme_one;
}
and
.theme_one{
$color: #000;
}
I've just come across the same issue myself. I wanted to have different colour themes for different sections of my site.
Using a mixin seems like the best way to go. It's nicely DRY, and easy to use. The trick is not setting your colours in your main styles blocks, but rather using only the mixin for this.
I've set up the theme colours as variables at the top so they can be edited nicely, and I've set them as lists so that multiple values can be passed without hordes of variable being defined.
So:
// Variable Definitions
$defaultColor: black white grey;
$color2: blue green brown;
$color3: red white blue;
#mixin colorSet($color: $defaultColor) {
$link: nth($color, 1);
$border: nth($color, 2);
$background: nth($color, 3);
border-color: $border;
background-color: $background;
.column {
border-color: lighten($border, 10%);
}
a {
color: $link;
&:hover {
color: darken($link, 15%);
}
}
}
// Default colours
body {
#include colorSet();
}
// Scoped colours
.my-theme-3 {
#include colorSet($color3);
}
.my-theme-2 {
#include colorSet($color2);
}
Will produce something like this:
body {
border-color: white;
background-color: grey; }
body .column {
border-color: white; }
body a {
color: black; }
body a:hover {
color: black; }
.my-theme-3 {
border-color: white;
background-color: blue; }
.my-theme-3 .column {
border-color: white; }
.my-theme-3 a {
color: red; }
.my-theme-3 a:hover {
color: #b30000; }
.my-theme-2 {
border-color: green;
background-color: brown; }
.my-theme-2 .column {
border-color: #00b300; }
.my-theme-2 a {
color: blue; }
.my-theme-2 a:hover {
color: #0000b3; }
Edit: Updated to use default mixin values.
In your case no need to use mixin, If you have set of many styles then use mixin,
ie. if you have
#mixin theme_one{
$color: #000;
height: 50px;
}
then use Mixin
otherwise for single property use only variable
$color: #fff;
.some_class01{
color: $color;
background: $color;
}
.some_class22{
border-color: $color;
}
IMP: Variable should assign at the top of your code, it means don't use it after/below where you assigned it :)
Not sure if this is what you are looking for. It looks like you may have tried something similar to this,
which should probably work. (it may just be a matter of using !default)
Your body tag with a class on it..
<body class="theme_one">
</body>
Sass variables defined in stylesheet..
//THEME ONE VARIABLES
.theme_one{
$borderColor:#333 !default;
$fontColor:#999 !default;
}
//THEME TWO VARIABLES
.theme_two{
$borderColor:#CCC !default;
$fontColor:#000 !default;
}
Pre-existing CSS which will be overwritten depending on which class is used on the body tag.
h1.someheader {
color:$fontColor;
border-bottom:1px solid;
border-color:$borderColor;
}
Otherwise you could maybe try something like this. It looks like you may have tried something similar, however there seems to be an error with your mixin ... see note below.
//mixin used to set variables for properties
#mixin themeOne($fontColor,$borderColor) {
color:$fontColor;
border-color:$borderColor;
}
#include themeOne(#000,#CCC);
Pre-existing CSS
h1.someheader {
color:$fontColor
border-color:$borderColor;
border-bottom:1px solid;
}
Also note in your mixin example you are using $color:#000; ... This won't be interpreited properly as it should be color:#000; You can't use variables as selectors
unless you do something like #{$color}:#000;
I haven't quite tested this yet, so some things might need to be adjusted. If this doesn't solve your problem I hope it at least gives you some ideas.