Calculate min / max of two values in Less

天大地大妈咪最大 提交于 2019-12-11 11:22:25

问题


How do i get the maximum or minimum of two values in Less. Just like Math.min() or Math.max() in javascript. I think this will be useful to use in your mixins.


回答1:


This feature has been implemented in the meantime. Have a look at the official Function Reference:

  • min()
  • max()



回答2:


Less min/max builtin functions are planned for future releases, see: https://github.com/less/less.js/pull/1371. For now you could try, based on https://stackoverflow.com/a/15982103/1596547:

.max(@a,@b)
{
   @max: ~"@{b}px";
}
.max(@a,@b) when (@a>@b)
{
   @max: ~"@{a}px";
}
.max(700,800);

.examplemax{width: @max;}

resulting in:

.examplemax {
  width: 800px;
}

or

.min(@a,@b)
{
   @min: ~"@{b}px";
}
.min(@a,@b) when (@a<@b)
{
   @min: ~"@{a}px";
}
.min(700,800);

.examplemin{width: @min;}

resulting in:

.examplemin {
  width: 700px;
}



回答3:


More Compact

I would use the inline javascript capability of LESS to achieve this and add a flexibility to the units (which could be set to a default of '' for just giving back the straight number if desired, but in my example default is px). Like so:

LESS

.minmax(@a,@b,@unit:'px') {
  @min: ~"`Math.min(@{a},@{b})`@{unit}";
  @max: ~"`Math.max(@{a},@{b})`@{unit}";
}
.test {
  .minmax(700,800);
  width: @max;
}
.test2 {
  .minmax(50,70,"%");
  width: @min;
}

CSS Output

.test {
  width: 800px;
}
.test2 {
  width: 50%;
}

Since you reference the javascript functions in your question, perhaps you were unaware of these inline capabilities that can interface with LESS.



来源:https://stackoverflow.com/questions/19345151/calculate-min-max-of-two-values-in-less

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!