4

I understand LESS doesn't have if/else structure and instead relies on guarded mixin statements. It doesn't appear to be able to set a LESS CSS variable inside of a mixin though.

Anyone have an idea of how I could implement something to the effect of.

if( ispercentage( @height ) {
  @height: "1024px";
}

// Calculations dependent on @height
@textAreaHeight = 0.5 * @height;
@buttonHeight = 0.2 * @height;

I've looked at several other stackoverflow questions including: LESS CSS - Setting variable within mixin

Community
  • 1
  • 1
blak3r
  • 16,066
  • 16
  • 78
  • 98

2 Answers2

2

Yes, it can be done. There was one bug that needed to be worked around.

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}
}

Example CSS Output

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;
}
ScottS
  • 71,703
  • 13
  • 126
  • 146
  • @blak3r--I [submitted the issue](https://github.com/cloudhead/less.js/issues/878) with passing of the variable. – ScottS Jul 26 '12 at 18:32
1

You can create a mixin that is "guarded" by the type, e.g.

.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 out, so I may have made a syntax mistake.

edit corrected syntax.

Luke Page
  • 8,136
  • 1
  • 20
  • 22
  • I don't think you can set a variable inside a mixin though. Can you? I tried playing around with it and couldn't get anything to compile. – blak3r Jul 12 '12 at 00:58