Using a general purpose selector as a mixin in LESS CSS

天涯浪子 提交于 2019-12-03 11:59:05

First off, I would strongly discourage doing such things. Instead, try to use the power of CSS and build your HTML such that the bootstrap rules apply, for example. Anyway, since you asked for it, here is the solution.

The problem is not the complexity of the selector, or the child rule, but the tag name selector part (i. e. the li). So, what we have to fix is the mixin parser only matching classes and ids. I guess we would not want to tamper with the first class or id test, since that is probably needed to distinguish mixins from normal CSS rules (although the tests run fine with that check commented out). (Actually, there is a parser preference in action, and the only thing tried after mixins are comments and directives, so we can safely remove that check as well). However, we can easily allow tag names in later parts of the mixin selector by adding a question mark after [#.] in the matching regular expression. So

while (e = $(/^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/)) {

– i. e. line 825 – becomes

while (e = $(/^[#.]?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/)) {

The test cases still run through fine, afterwards, but subtle breakage my occur, so be cautious.

Edit: There is a GitHub Issue for the same problem. Apparently the less folks rather want the mixin feature to be more narrow and function-like, instead of allowing a more flexible … well … mixing in of rules. With regard to the CSS output, that's probably reasonable.

Gaurav Ramanan

This is possible since version 1.4.0 (2013-06-05) of LESS that include the extend feature. Based on the original example

.navbar .nav > li {
  float: left;
}

.mynavbar:extend(.navbar .nav > li) {}

compiles to

.navbar .nav > li,
.mynavbar {
  float: left;
}

Documentation here and discussion & example use for the original question here

EDIT: Added Code Sample

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