Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User defined functions with LessCSS?

Tags:

less

I have just recently gotten into LessCSS and I am running into what I feel is major limitation and I was wondering if there was a way to do this?? I want to say I read somewhere that Sass allows for user defined functions but will LessCSS do the same?

What I'm wanting to do:

@fs: 16;

// either return the value
.s(@t,@s,@u) {
    // return @t/@s*@u;
}
#elem {
    margin-top: .s(30,@fs,1em);
    width: .s(900,@fs,1em);
    .child {
        width: .s(100,900,100%);
    }
}

// or have a property argument
.s(@t,@s,@u,@p) {
    @{p}: @t/@s*@u;
}
#elem {
    .s(30,@fs,1em,margin-top);
    .s(900,@fs,1em,width);
    .child {
        .s(100,900,100%,width);
    }
}

The only way I can figure it out, but it is very limited because I have to have multiple mixins:

.s(@t,@s,@u,@p) when (@p = margin-top) { margin-top: @t/@s*@u; }
// margin[-top|-right|-bottom|-left]
// padding[-top|-right|-bottom|-left]
.s(@t,@s,@u,@p) when (@p = width) { width: @t/@s*@u; }
.s(@t,@s,@u,@p) when (@p = height) { height: @t/@s*@u; }

I know I can always modify the less.js file to add a spacing function like the built-in round() or ceil() function. But, that kills the option of compiling the .less files for production using LessPHP, Crunch, SimpLess.

like image 373
Nathan L. Avatar asked Mar 31 '12 18:03

Nathan L.


1 Answers

As far as I know, there's no property argument: you must write it down.

That is, a function will return a calculated value or instruction(s) (property/ies and calculated values).

There aren't thousands of properties in CSS, it's not a CMS with hundreds of classes and functions, so your list won't be as long as you can imagine. You should use other CSS preprocessors or a backend language to generate your CSS if you want to do such complicated things. Or better keep it simple.
That said, lessphp allows for user functions:

lessphp has a simple extension interface where you can implement user functions that will be exposed in LESS code during the compile. They can be a little tricky though because you need to work with the lessphp type system.

like image 163
FelipeAls Avatar answered Jan 03 '23 00:01

FelipeAls