Can you set a variable inside mixin in LESS CSS?

I understand that LESS does not have an if / else structure and instead relies on protected mixin statements. It seems like it cannot set the LESS CSS variable inside mixin.

Does anyone have an idea of ​​how I can implement something in action.

if( ispercentage( @height ) { @height: "1024px"; } // Calculations dependent on @height @textAreaHeight = 0.5 * @height; @buttonHeight = 0.2 * @height; 

I looked at several other stackoverflow related issues, including: LESS CSS - setting a variable in mixin

+4
source share
2 answers

Yes, it can be done. There was one mistake that needed to be worked on.

Example LESS code

 //Set up guarded mixins .setHeight(@h) when (ispercentage(@h)) { @height: 1024px; } .setHeight(@h) when not (ispercentage(@h)) { @height: @h; } //set up main height @mainHeight: 50%; body { height: @mainHeight;} //call it by itself to make global //.setHeight(@mainHeight); <-this failed (appears to be a bug) .setHeight(50%); // <-this worked .subsection { height: @height; /* just to show it is setting it */} //use it for other globals @textAreaHeight: 0.5 * @height; @buttonHeight: 0.2 * @height; textarea { height: @textAreaHeight} button { height: @buttonHeight} //override it locally body.fixedHeight { .setHeight(300px); @textAreaHeight: 0.333 * @height; height: @height; textarea { height: @textAreaHeight} } 

CSS output example

 body { height: 50%; } .subsection { height: 1024px; /* just to show it is setting it */ } textarea { height: 512px; } button { height: 204.8px; } body.fixedHeight { height: 300px; } body.fixedHeight textarea { height: 99.9px; } 
+2
source

You can create a mixin that is "protected" by a type, for example.

 .doHeightSet(@height) when ispercentage(@height) { .doheightSet(1024px) } .doHeightSet(@height) when not ispercentage(@height) { // Calculations dependent on @height @textAreaHeight: 0.5 * @height; @buttonHeight: 0.2 * @height; /* use variables here */ } 

Sorry, I don’t have time to try this, so I may have made a syntax error.

change the correct syntax.

+1
source

All Articles