1

I have a SCSS file that contains CSS. I want to extend those classes yet I don't want to render those on my main file (refer below).

File structure:

_vars.scss
main.scss

main.scss

@import 'vars';
//extend margin class
body{
    margin: @extend .m10;
}

In my _vars.scss

.m10{margin:10px;}
.p10{padding:10px;}

If the main SCSS is compiled, it will be compiled to:

main.css

.m10{margin:10px;} /* <-- i dont want to see this in my compiled scss --> */
.p10{padding:10px;} /* <-- i dont want to see this in my compiled scss --> */
body{
    margin: 10px;  /* <-- but still extent from the .m10 class of _vars.scss --> */
}

Any ideas to not display those classes from the _vars.scss yet still extending those classes in the main.scss? Is there a way to do that with SASS?

Robert Wade
  • 4,918
  • 1
  • 16
  • 35
Juliver Galleto
  • 8,831
  • 27
  • 86
  • 164

2 Answers2

3

The way to go is to use placeholders instead of classes:

_vars.scss:

%m10 {
  margin:10px;
}
%p10 { 
  padding:10px;
}

main.scss

@import 'vars';
body {
  @extend %m10; 
}

Which produces, compiled:

body{
  margin: 10px;
}

Placeholders only produce CSS if they are used. Better, they'll concatenate all selectors using them, to avoid duplicate contents:

body {
  @extend %m10;
  background: red;
}
main > article {
  @extend %m10;
}

Will outputs:

body, main > article {
  margin: 10px;
}
body {
  background: red;
}
zessx
  • 68,042
  • 28
  • 135
  • 158
2

The output you get is exactly what it's supposed to be.

If you don't want to have:

.m10{margin:10px;} /* <-- i dont want to see this in my compiled scss --> */
.p10{padding:10px;} /* <-- i dont want to see this in my compiled scss --> 
*/
body{
margin: 10px;  /* <-- but still extent from the .m10 class of _vars.scss --> 
*/

}

You shouldn't use a class and an @extend but a mixin and an @include

Here is what you could do:

@mixin m10 {
  margin: 10px;
}

body{
  @include m10;
}

It would even be better to add a variable :

@mixin myMargin($size) {
  margin: #{$size}px;
}

.input {
   @include myMargin(10);
}

This way, you can choose your margin size.

Amaury Hanser
  • 3,191
  • 12
  • 30