Use less to generate dynamic CSS rules based on parameter value and passed mixin

偶尔善良 提交于 2019-12-06 12:27:34

问题


It is possible to achieve something like this in LESS?

.some-button(@className) {
  @className { .actionIcon; }
  tr:hover {
    @className { .actionButton; }
  }
}

When I call it:

.some-button(.edit-action);

The expected output should be :

.edit-action { .actionIcon; }
tr:hover { .edit-action { .actionButton; } }

Currently I'm getting this "Unrecognized input in @className { .actionIcon; }" error:

.some-button(@className) {
  @className { .actionIcon; }
  tr:hover {

EDIT

Another thing I would like to achieve is to use a mixin as mixin parameter:

.actionButton(@buttonClassName; @buttonType) {
  @{buttonClassName} { 
    .actionIcon; 
  }
  tr:hover {
    @{buttonClassName} { 
        .actionHoverIcon; 
        @buttonType();
    }
  }
}

and call is like this:

.actionButton(~'.row-edit', button-harmful);

where button-harmful is a mixin.


回答1:


They call this "Selector Interpolation", the correct syntax is:

.some-button(@className) {
    @{className} { 
        /* ... */
    }
}

// usage:
.some-button(~'.edit-action');

Or alternatively (if you know you will use only classes, i.e. . prefixed selectors) like this:

.some-button(@className) {
    .@{className} {
        /* ... */
    }
}

// usage:
.some-button(edit-action);



回答2:


To answer your second question (i.e. "use a mixin as mixin parameter"): in short, currently this is impossible in a straight forward way. There're a few workarounds that simulate this functionality though (You'll find a brief of those methods here and here).

For example:

.actionButton(@buttonClassName, @buttonType) {
    @{buttonClassName} {
        .actionIcon;
    }
    tr:hover {
        @{buttonClassName} {
            .actionHoverIcon;
            .call(@buttonType);
        }
    }
}

// usage:

.call(button-harmful) {.button-harmful}
.actionButton(~'.row-edit', button-harmful);


来源:https://stackoverflow.com/questions/21600201/use-less-to-generate-dynamic-css-rules-based-on-parameter-value-and-passed-mixin

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