Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

css - LESS: Inheritance using a variable

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...