1

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?

Moring
  • 13
  • 3

2 Answers2

1

To acheived expected result of margin-bottom , use below workaround to use mixin with one value.

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

https://codepen.io/nagasai/pen/wqdEZr

Please check the compiled CSS below

div {
  margin-top: 1em;
  margin-bottom: 2em;
}
Naga Sai A
  • 10,771
  • 1
  • 21
  • 40
  • I don't think this covers what he wants. Rather than using 16 and 32, try 16 and 24. Sure you can move the math out and do `@emSpacing * 24/16` but then why even have the mixin? – Don Aug 09 '17 at 20:28
  • That's essentially what we're doing now but then you run into things like this: `font-size: (@font-size / 1.15);` which is too rigid (that 1.15 will likely need to be adjusted if the value of `@font-size` was increased/reduced), involves too much math, and isn't easily conceivable for others who may edit these files in the future. – Moring Aug 10 '17 at 12:35
0

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.

Community
  • 1
  • 1
Don
  • 3,987
  • 15
  • 32