csslessless-mixins

LESS CSS Functions: Utilize Different Values


With LESS, I'm trying to come up with a snappy way to calculate margins, paddings, and the like based upon defining an amount.

Currently, I'm specifying this:

    .emSpacing(@string) {
        @emSpacing: unit(@string / 16) + 0em;
    }

and call it:

    div {
        .emSpacing(16);
        margin-top: @emSpacing;
        margin-bottom: 2em;
    }

which outputs a margin-top of 1em. However, applying that .emSpacing(16) to the margin-bottom won't work without some math to get to that desired 2em.

Ideally, I'd like to do something like this:

    div {
        margin-top: @emSpacing(16);
        margin-bottom: @emSpacing(32);
    }

which, of course, doesn't work. Is there another solution on these simple lines which will work?


Solution

  • You could use the & selector and just put it there twice. This pulls the mixins into 2 different scopes and keeps them from conflicting with one another. It's a bit hacky and not the cleanest looking thing but it does work, like so:

    div {
      &{
        .emSpacing(16);
        margin-top: @emSpacing;
      }
      &{
        .emSpacing(32);
        margin-bottom: @emSpacing;
      }
    }
    

    This allows you to use the mixin twice with 2 different values using the same as the parent's selector. You'd then group all the properties you want to use that value into the same block.

    You could clean up the look of single line uses a bit by doing something like:

    div {
      &{.emSpacing(16); margin-top: @emSpacing;}
      &{.emSpacing(32); margin-bottom: @emSpacing;}
    }
    

    Still don't think it's super clean though it doesn't seem there's an alternative.

    Edit

    Looks like there's a plugin that would give you the format you want.

    Less Plugin Functions

    Instructions on use are in the readme.