LESS building a string in a loop for dynamic gradient

只谈情不闲聊 提交于 2019-11-29 16:41:20

If I understand the goal correctly what you need is "Property Values Merge" feature so together with certain "Pattern-matching" optimizations the mixin could look like (assuming Less 1.7.x or higher, but I tested this only with v2):

// usage:

@gray:  #010101;
@white: #020202;
@black: #030303;

@gradients: @gray 0%, @white 30%, @black 100%;

div {
    .make-gradient(@gradients, left);
    // or just:
    // .make-gradient(@gray 0%, @white 30%, @black 100%; left);
}

// impl.:

.make-gradient(@gradients, @direction, @fade: 50%) {
    background+: ~"linear-gradient(" @dir;
    .loop(length(@gradients));
    .loop(@i) when (@i > 0) {
        .loop((@i - 1));
        @gradient: extract(@gradients, @i);
        @color:    extract(@gradient, 1);
        @stop:     extract(@gradient, 2);
        background+: fade(@color, @fade) @stop;
    }
    background+_:);

    .dir(@direction);
    .dir(@dir_) {@dir: @dir_}
    .dir(left)  {@dir: to right}
    .dir(top)   {@dir: to bottom}
}

I did not include any vendor prefixing because of tools like Autoprefixer (especially since it's now included as a plugin for Less v2), but I guess you'll easily add that yourself if you still find such kludge worthy.

P.S. As suggested in comments below: background+_:); works only in v2 (so it's more like an unintended bogus), more safe syntax is obviously background+_: ~")";

You could just use this mixin I created a few weeks back,...

Rotatable Multi-stop SVG linear gradient mixin It is as simple as,...

.multigradient(rgb; 168; @rgb; 2, 1);  // id; degrees; colorstring; ratio

once you've built your colorstring eg.,...

@rgb: red 0, green 50%, blue 100%;

If you look at the code in this mixin, there is a function which builds an svg 'colorstop' string by looping through multiple values.

Enjoy! :)

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