Auto-generate LESS styles for sprite icons

只谈情不闲聊 提交于 2019-12-04 19:03:57

Pure LESS (assuming you're using Web Essentials 2013 which uses LESS 1.5.x):

@icons: upvote, downvote, comment, new, notify, search, popup, eye, cross;

.iconize();
.iconize(@i: length(@icons)) when (@i > 0) {
    .iconize((@i - 1)); 

    @value: extract(@icons, @i); // LESS arrays are 1-based
    .@{value}       {background-position: (-20px * (@i - 1)) 0}
    .color.@{value} {background-position: (-20px * (@i - 1)) -20px}
    .white.@{value} {background-position: (-20px * (@i - 1)) -40px}
}

I removed & from selector names since it has no effect when you generate these classes in the global scope (but put it back if you actually need .iconize to be nested in another ruleset). It is also possible to calculate array length in earlier LESS versions (that have no length function) w/o any javascript, but I don't list this method here since it's quite scary (and you don't need it anyway).


Your javascript based loop is in fact less or more correct but the problem is all values returned by LESS inline javascript are of so-called "anonymous value" type and not a numbers so that when (@c < @count) condition is always true and the loop becomes infinite. (basically the condition is expanded exactly as when (0 < ~'9') ... when (9 < ~'9') = true etc.)

Bass Jobsen

I think it depends on the version of LESS you use. Different versions of LESS handle array like structures and their length different.

Since LESS 1.5 you can define an array with quotes, like:

@array: "value1","value2"; and calculate its length with length(@array).

For example see also: Sprites LESS CSS Variable increment issue

With LESS 1.5 your code ends in an endless loop: "SyntaxError: Maximum call stack size exceeded in"

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