How to reuse css class content in another class without copying?

前端 未结 8 1079
北恋
北恋 2021-02-18 14:07

Is it possible to use existing css class as content in another class ?

I mean something like:

Contained in some library:
.class1 { text-indent: 100 }

 I         


        
8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-18 14:34

    You mentioned in one comment that you cannot use LESS, but I think perhaps you misunderstand how LESS (or another preprocessor) could help you. That is, you have not given any reason that I can see why you cannot use it (even in your update). As I understand your problem, you have the following parameters:

    1. Cannot change html
    2. Cannot change the css file that defines .class1.
    3. You can change the css file that defines .class2.

    If the above is correct, then here is how you use LESS (version 1.5+). You make your file defining .class2 a .less file. Then, to keep it clean, I believe you are going to have to do a two step process (it may be you can do step 2 without step 1).

    Step One: Make the CSS into LESS

    Create a file, let's say CSStoLESS.less and put this in it:

    @import (less) /path/to/your/your-css-defining-class1.css;
    

    This will import the css and make the processor consider it as LESS code. It is possible that the next step does that as well, I have not had opportunity to test it out.

    Step Two: Use that file as reference in your LESS

    By doing this in your .less file defining .class2:

    @import (reference) /path/to/your/CSStoLESS.less;
    
    .class2 { .class1; }
    

    You are importing the previous css file that has been converted to less as reference only. This prevents you from getting duplicate selectors for .class1 or anything else contained in your original css file. Now you can use an inclusion of .class1 just like you show in your question to make the properties of .class1 become that of .class2.

    It may be that this alone works:

    @import (reference) /path/to/your/your-css-defining-class1.css;
    
    .class2 { .class1; }
    

    What I don't know is if the (reference) inclusion also defaults to making .css into LESS code like the (less) inclusion typecasting does in step one. I need to research this out more. If so, then it is a one-step, not a two-step process.

提交回复
热议问题