LESS: Inheritance using a variable

2020-02-07 07:11发布

I am learning to use a CSS preprocessor for the first time (LESS) and having trouble with trying to define a class which inherits a class when that parent class is a variable name..

This is basically what I want to do:

@import "font-awesome/font-awesome.less"

.icon-application-home{
    .fa .fa-home;
}

but as fa is defined in Font Awesome as this:

@fa-css-prefix:       fa;

then the less won't compile, because it doesn't recognize .fa. So I tried this instead:

@import "font-awesome/font-awesome.less"

.icon-application-home{
    .@{fa-css-prefix} .@{fa-css-prefix}-home;
}

However that is not working either. Is there any workaround? What can I do here?

EDIT

I found half an answer here:

Missing Font-Awesome.less variables in my .less file after importing

This works (partly) if I do the following:

@import (less) "../font-awesome.css";

.icon-home {
    .fa;
}

However, I noticed that .fa-home does not exist... only .fa-home:before... so I tried this:

@import (less) "../font-awesome.css";

.icon-home {
    .fa;
    .fa-home:before;
}

and

@import (less) "../font-awesome.css";

    .icon-home {
        .fa;
    }
    .icon-home:before {
        .fa-home:before;
    }

neither of these work. Any ideas?

1条回答
相关推荐>>
2楼-- · 2020-02-07 07:52

Assuming you use WE2012 that includes Less 1.4.2 the simplest solution would be:

@import (less) "../font-awesome.css";

.icon-application-home {
    &:extend(.fa, .fa-home all);
}

Or:

@import (less) "../font-awesome.css";

.icon-application-home
    :extend(.fa, .fa-home all) {

}   

Read extend documentation for details on how this stuff works.


If you upgrade to an IDE/Compiler incorporating Less 1.6.x you will be able to do:

@import ".../font-awesome.less"

.icon-application-home {
    .fa;
    &:before {content: @fa-var-home}
}

There you still can't use .fa-home or .fa-home:before as mixins since the first is not defined and the second is not valid mixin selector, fortunately &:before {content: @fa-var-home} is just what .fa-home does. In general though, the extend based solution is more optimal since it produces more compact CSS.

查看更多
登录 后发表回答