SASS - Extend class across multiple files

牧云@^-^@ 提交于 2019-12-04 22:57:15

问题


I have a project that uses Compass with SASS/SCSS. It is a single page application.

I have a master .scss file that holds all of my variables, mixins and function declarations.

//Master.scss 
$foo: 'bar';

@function border($color) {
  @return 1px solid $color;
}

// etc.

I have a base.scss file that has the main UI's css.

My system uses AMD to import other modules later on, after load. This means some stylesheets are loaded after the fact.

Each module, or 'App's stylesheet imports the master .scss file, which has all of the variables, etc. The master.scss does not have any actual class declarations, so there are no duplicate imports when a module is loaded.

Now, I prefer using @extend over mixins where I am repeating the same code. Such as:

.a { @extend .stretch; }

Instead of:

.a { @include stretch(); },

Which both produce the same result:

.a { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; }

Doing an extend is better, as then a repeat of that code is not splattered all over the place. Doing this:

.stretch { @include stretch() }
.a { @extend .stretch; }
.b { @extend .stretch; }
.c { @extend .stretch; }

Only produces:

.stretch, .a, .b, .c { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; }

As opposed to:

.a { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; }
.b { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; }
.b { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; }

So we like extend. Now the only problem, is that if I put the extendable class (.stretch) into the master.scss file, it will copy itself to every single css page. If I put it into the base.scss file, Compass does not seem to recognize the class when compiling and so does not extend it.

Not sure what the best way to go to solve this is. My exact question then, is:

How do I extend a css class across multiple files while only declaring it once?


回答1:


That's what placeholders made for. Instead of this:

.stretch { color: #F00 }
.a { @extend .stretch; }
.b { @extend .stretch; }
.c { @extend .stretch; }

use this:

%stretch { color: #F00 }
.a { @extend %stretch; }
.b { @extend %stretch; }
.c { @extend %stretch; }

It will produce the following css:

.a, .b, .c {
  color: red; 
}

I.e. the stretch class is not included in the final compiled CSS, but you could still use it in SASS.




回答2:


Use the @import method in Sass. This makes available to another sass file all the mixings, variables and more.

http://sass-lang.com/tutorial.html

in origin.sass

$variable_color = #877889

.one, .another, .two
  @extend .fatherclass

in another.sass

@import origin

.one
  color: $variable_color


来源:https://stackoverflow.com/questions/18807839/sass-extend-class-across-multiple-files

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