Defining Variable Variables using LESS CSS - css

Say I have three separate color schemes that are used on various pages in a site. Each color has a a light, medium and dark tint defined, and the color scheme is defined by a class in the body. Assume that the "red" color scheme is the default. Like this:
Color Definitions:
#red-lt: #121;
#red-md: #232;
#red-dk: #343;
#green-lt: #454;
#green-md: #565;
#green-dk: #676;
#blue-lt: #787;
#blue-md: #898;
#blue-dk: #909;
Basic Default Style Example
body { background-color: #red-dk;
#container { background-color: #red-md;
p { color: #red-dk; }
}
}
Different Color Scheme Style Example
body.green { background-color: #green-dk;
#container { background-color: #green-md;
p { color: #green-dk; }
}
}
I'd like to use variables so that I don't have to re-write all of the color variations for each scheme, so that I can just write something like this:
body.[color-var] { background-color: #[color-var]-dk;
#container { background-color: #[color-var]-md;
p { color: #[color-var]-dk; }
}
}
…but I can't quite wrap my head around how to accomplish that. Help…?

Use interpolation and escaping, parentheses in the selector and parametric mixins to get the desired effect:
Dynamic variables by interpolation: In a string, "#{variable}" is replaced with the value of the variable. They can also be nested: Given #{#{var}-foo} and #var: bar;, the result is "barfoo".
The resulting value is quoted. To remove these quotes, prefix ~.
Dynamic selectors by Selector interpolation: body.#{var} turns into body.bar.
Example:
#red-md: #232;
#red-dk: #343;
.setColor(#color) {
body.#{color} { background-color: ~"#{#{color}-dk}";
#container { background-color: ~"#{#{color}-md}";
p { color: ~"#{#{color}-md}"; }
}
}
}
.setColor(~"red"); // Escape to prevent "red" turning "#FF0000"
//.setColor(~"blue"); etc..
Turns into:
body.red {
background-color: #334433;
}
body.red #container {
background-color: #223322;
}
body.red #container p {
color: #223322;
}
Note: When the answer was originally written, selector interpolation did not exist. See the previous revision for the solution if you're working with an old LESS compiler (before LESS 1.3.1a). Support for the old method will be dropped in LESS 1.4.0.

If those values really follow a predictable format like that, seems like a perfect case for a parametric mixin:
Less:
#red: #232;
#green: #565;
#blue: #898;
.theme (#color) {
background-color: #color - #111;
#container {
background-color: #color;
p { color: #color + #111; }
}
}
body.red {
.theme(#red);
}
Compiled CSS:
body.red{background-color:#112211;}
body.red #container{background-color:#223322;}
body.red #container p{color:#334433;}

I know this question is pretty old, but for those that come to this post my answer maybe can help
I`m not really sure for what you want to use this, but one of my suggestion is based on #ScottS answer. On my real world, I need to create a web app, where it would show several brands and each brand have their own text color, background and so on... so I started to chase a way to accomplish this in LESS, what I could easily do on SASS and the result is below:
LESS
// Code from Seven Phase Max
// ............................................................
// .for
.for(#i, #n) {.-each(#i)}
.for(#n) when (isnumber(#n)) {.for(1, #n)}
.for(#i, #n) when not (#i = #n) {
.for((#i + (#n - #i) / abs(#n - #i)), #n);
}
// ............................................................
// .for-each
.for(#array) when (default()) {.for-impl_(length(#array))}
.for-impl_(#i) when (#i > 1) {.for-impl_((#i - 1))}
.for-impl_(#i) {.-each(extract(#array, #i))}
// Brands
#dodge : "dodge";
#ford : "ford";
#chev : "chev";
// Colors
#dodge-color : "#fff";
#ford-color : "#000";
#chev-color : "#ff0";
// Setting variables and escaping than
#brands: ~"dodge" ~"ford" ~"chev";
// Define our variable
.define(#var) {
#brand-color: '#{var}-color';
}
// Starting the mixin
.color() {
// Generating the loop to each brand
.for(#brands); .-each(#name) {
// After loop happens, it checks what brand is being called
.define(#name);
// When the brand is found, match the selector and color
.brand-#{name} & {
color: ##brand-color;
}
}
}
.carColor {
.color();
}
Te result will be:
CSS
.brand-dodge .carColor {
color: "#fff";
}
.brand-ford .carColor {
color: "#000";
}
.brand-chev .carColor {
color: "#ff0";
}
This is very tricky and I had to use several elements to get what I needed, first used a set of mixins provided by Seven Phase Max and you can find it here and than, the #ScottS answer was the piece that was missing fro my puzzle... hope this helps you and others that need to create a set of Variables to be part of another variable and create a more dynamic less file.
You can copy my entire code and test at http://lesstester.com/

Try this
#red-lt: #121;
#red-md: #232;
#red-dk: #343;
#green-lt: #454;
#green-md: #565;
#green-dk: #676;
#blue-lt: #787;
#blue-md: #898;
#blue-dk: #909;
#color: 'red-lt';
div{
background: ##color;
border: 1px solid lighten(##color,20%);
}

To my knowledge, variable variable names are not supported in LESS. You could however restructure your declarations in a more semantic manner:
/* declare palette */
#red-lt: #121;
#red-md: #232;
#red-dk: #343;
#green-lt: #454;
#green-md: #565;
#green-dk: #676;
#blue-lt: #787;
#blue-md: #898;
#blue-dk: #909;
/* declare variables based on palette colors */
#lt: #red-lt;
#md: #red-md;
#dk: #red-dk;
/* ...and only use them for main declarations */
body { background-color: #dk;
#container { background-color: #md;
p { color: #dk; }
}
}
This should let you switch between palettes quite painlessly by avoiding explicit color references.

Related

SASS Customize Class Names with Variables

Is there any way to customize the variables in SASS?
For example:
.m-b-{$number} {
margin-bottom: $number;
}
If I give class="m-b-50" to an element, it should take margin-bottom 50. I just want to know if it is possible with SASS.
Yes it is possible with the help of variable interpolation or variable substitution which uses #{} for variable substitution in SASS and mixins which is a block of code just like function.
Interpolation is the process of evaluating an expression or a string containing one or more variables, yielding a result in which the variables are replaced with their corresponding values.
Simple example of interpolation and set values to the css property in SASS:
$number:60;
$n: 20px;
.m-b-#{$number}{
margin-bottom: #{$number}px;
margin-top: $n;
}
To create customize class names, will use mixins:
#mixin margin-class($side, $number) {
$firstLetter: str-slice($side, 0, 1);
.m-#{$firstLetter}-#{$number}{
margin-#{$side}: #{$number}px;
}
}
$margins: (10, 20);
$sides: ("top", "right", "bottom", "left");
#mixin generate-margin(){
#each $margin in $margins{
#each $side in $sides{
#include margin-class($side, $margin);
}
}
}
#include generate-margin();
Here, generate-margin() will get executed which will call margin-class() for each $margins and $sides, and will generate the below CSS classes:
.m-t-10 {
margin-top: 10px;
}
.m-r-10 {
margin-right: 10px;
}
.m-b-10 {
margin-bottom: 10px;
}
.m-l-10 {
margin-left: 10px;
}
.m-t-20 {
margin-top: 20px;
}
.m-r-20 {
margin-right: 20px;
}
.m-b-20 {
margin-bottom: 20px;
}
.m-l-20 {
margin-left: 20px;
}
That's the one way when you want only for specific values, but if you want to create margin class for 0-20, you can loop thru 0 to 20 as shown below:
#mixin generate-margin(){
#for $margin from 1 through 20{
#each $side in $sides{
#include margin-class($side, $margin);
}
}
}
For anyone else facing this issue, here is how one can achieve this:-
#for $i from 1 through 10 {
.mb-#{$i} {
margin-bottom: #{$i}rem;
}
}
The answer is: no it is not possible. SASS is just a language to pre-generate CSS for you. There is no on-demand, dynamic creation of classes triggered by the contents of your HTML markup. When it comes time for the browser to render your HTML and apply your specified classes, it is still just using CSS. I.e. if you assign class="m-b-50" to an element, the class .m-b-50 must already be explicitly defined somewhere. As noted in the other answers, SASS can make it easier to generate a bunch of pre-defined classes but you must know which values you want to support up front.
Now, you could generate classes for some very large, all-inclusive range like -1000 to 1000 to effectively support all values you might ever try to use and it would seem to do what you wanted, but you would be forcing your users to download a larger CSS file with, most likely, a large percentage of it being unused CSS which is wasteful and can be inconsiderate in a world of paid & limited data plans.

Less.js: if #color = value do something

Lets asume that i have a variable:
#title: blue;
And i need to know if there is anyway with the iscolor function to do something if the value is blue.
For example, if #title = blue import a #mixin to a class called "mytitle"
Im not really understanding the iscolor function and behavior
Thanks in advance
If I understand your question correctly, what you are trying to do is extremely simple:
#title: blue;
.mytitle when (#title = blue){
/*Do stuff here*/
}
If #title's value is equal to blue, add styles to .mytitle
iscolor is not appropriate here - it simply evaluates a string and tells you if the string is a valid color string. So trying something like iscolor(#title) will return true regardless of the color (as long as #title contains a valid color string).
Update: I think you're looking for the Mixin Guard feature:
.mixin (#a) when (lightness(#a) >= 50%) {
background-color: black;
}
.mixin (#a) when (lightness(#a) < 50%) {
background-color: white;
}
.mixin (#a) {
color: #a;
}

How to output CSS counter from Sass mixin

I am writing a mixin that I want to output a CSS counter. Here's my goal:
.selector:nth-child(3n+1) {
color: green;
}
That makes every three elements, starting with the first, green.
I would like my mixin to take that first number, in my example 3 and output the CSS. Something like this:
#mixin counter($number) {
&:nth-child($number * n + 1) {
color: green;
}
}
Is this possible in Sass at this point?
To use a variable's value in the selector, you should use the interpolation syntax #{} and append the n to it like in the below code block.
#mixin counter($number) {
&:nth-child(#{$number}n + 1) {
color: green;
}
}
.selector{
#include counter(3);
}
The above code compiles successfully and produces the required output when tested using the online compiler at sassmeister.com.

Less syntax with ## meaning

I have downloaded a theme for bootstrap and In their less sources I have a mixin like:
.label-color(#color) {
#label-class:~"label-#{color}";
#badge-class:~"badge-#{color}";
#label-color:##label-class;
.#{label-class}, .#{badge-class} {
background-color:#label-color !important;
}
}
.label-arrow(#color) {
#label-class:~"label-#{color}";
#label-color:##label-class;
.#{label-class}{
&.arrowed:before {
border-right-color:#label-color;
}
&.arrowed-in:before {
border-color:#label-color;
}
&.arrowed-right:after {
border-left-color:#label-color;
}
&.arrowed-in-right:after {
border-color:#label-color;
}
}
}
.label-color(~"lime");
.label-color(~"red");
My problem is that #label-color:##label-class;
because my internal compiler less4j give me error at this double ## and I don't understand why. Local compiler Crunch is working and know to compile that so is not a wrong syntax.
Can someone give me a hint pls, ty.
As already mentioned by #deceze, you can read at http://lesscss.org/features/#variables-feature-variable-names that the double # will be use to create a variable variable name in Less:
For instance:
#red: darkred;
#color: "red";
p {
color: ##color;
}
Outputs:
p {
color: darkred;
}
Notice that the variable name (#color) should be a string.
The above should also work in less4j according the docs which can be found at: https://github.com/SomMeri/less4j/wiki/Less-Language-Variables:
If the variable contains a string, then it can act as a reference to
another variable.

sass, custom selectors based on parent

I have the following mixins to make easy work with BEM syntax, sass 3.3.2 code:
=b($name)
.#{$name}
#content
=e($name)
&__#{$name}
#content
=m($name)
&--#{$name}
#content
+b(menu)
+e(item)
color: grey
+e(item)
+m(alert)
color: red
This gives me the desired result:
.menu__item {color: grey;}
.menu__item--alert {color: red;}
So this works pretty nice for element level modifiers, however when i want to have block level modifiers the problem begins:
+b(menu)
+m(theme-1)
+e(item)
color: blue
css output:
.menu--theme-1__item {color: blue;}
when the thing i really want is this:
.menu--theme-1 .menu__item {color: blue;}
So i need a way to check what the context of an element is, when the context is a block there is no problem but when is a modifier the syntax fails. I tried inside e mixin to take the parent selector as string, so when e parent is b it will not have the -- syntax, in the other way when his parent is m it will have the -- syntax, with that i could decide what syntax use for both context.
I didn't find a way to take the parent selector as a string and i think is not possible, is there a way to make this works?
Update
I found a not very straightforward solution with it works fine, it uses a context argument in the element mixin:
=e($name, $context:null)
#if $context
&
+b($context)
&__#{$name}
#content
#else
&__#{$name}
#content
Now i can call the mixin as follows:
+b(menu)
+m(theme-1)
+e(item, nav)
color: blue
getting:
.menu--theme-1 .menu__item {color: blue;}
Answering a 2 year old question - long shot :) But hopefully could help someone else as well.
So a more robust way would be to improve your Element mixin to check if the parent selector has a modifier.
So you would need 2 functions:
one to check if a selector contains a modifier
one to get the block name from that selector
#function _bem-selector-has-modifier($selector) {
$selector: _bem-selector-to-string($selector);
#if str-index($selector, $bem-modifier-separator) or str-index($selector, ':') {
#return true;
} #else {
#return false;
}
}
#function _bem-get-block-name($selector) {
$selector: _bem-selector-to-string($selector);
$modifier-separator: '--';
$modifier-start: str-index($selector, $modifier-separator) - 1;
#return str-slice($selector, 0, $modifier-start);
}
And then you just need to apply the check in your element mixin
$bem-element-separator: '__';
#mixin element($element) {
$selector: &;
#if _bem-selector-has-modifier($selector) {
$block: _bem-get-block-name($selector);
#at-root {
#{$selector} {
.#{$block + '__' + $element} {
#content;
}
}
}
} #else {
#at-root {
#{$selector +'__' + $element} {
#content;
}
}
}
}
So calling element('item') inside a modifier('with-modifier') should render a .block--with-modifier .block__item selector in your compiled CSS and you won't have to manually pass the context.
The code posted is SCSS, but the idea should be the same with SASS.

Resources