Question

I'm trying to clean up my CSS to be cleaner by using SCSS.

Standard CSS:

.dark-hr,
.light-hr { 
  width: 100%;
  height: 1px;
  margin: 15px 0px;
}
.dark-hr {
  background-color: #595959;
}
.light-hr {
  background-color: #cccccc;
}

vs SCSS:

.generic-hr { 
  width: 100%;
  height: 1px;
  margin: 15px 0px;
}
.dark-hr {
  @extend .generic-hr;
  background-color: #595959;
}
.light-hr {
  @extend .generic-hr;
  background-color: #cccccc;
}

Is there any way to avoid creating the 'generic-hr' class that won't be used? I was hoping that some kind of nest would work well. In this scenario the CSS is definitely way cleaner and more readable than SCSS.

Ideally I would need this to work in SCSS:

.## {
  // base class that is not outputted
  .dark-hr {
    //attributes the extend the base class '.##'
  }
  .light-hr {
    //attributes the extend the base class '.##'
  }
}

OUTPUT:

 .dark-hr, .light-hr {
   //shared attributes defined by '.##'
 }
 .dark-hr {
   // overrides
 }
 .light-hr {
   // overrides
 }
Was it helpful?

Solution

What you're wanting to use is an extend class (I call them "silent classes"), which is signified by using a % instead of a ..

hr%base { 
  width: 100%;
  height: 1px;
  margin: 15px 0px;
}
.dark-hr {
  @extend hr%base;
  background-color: #595959;
}
.light-hr {
  @extend hr%base;
  background-color: #cccccc;
}

OTHER TIPS

Wouldn't you normally do something like this:

.generic-hr { 
  width: 100%;
  height: 1px;
  margin: 15px 0px;
  &.dark {
    background-color: #595959;
  }
  &.light {
    background-color: #cccccc;
  }
}

My pattern for this kind of thing is a mixin:

@mixin generic-hr { 
  width: 100%;
  height: 1px;
  margin: 15px 0px;
}
.dark-hr {
  @include generic-hr;
  background-color: #595959;
}
.light-hr {
  @include generic-hr;
  background-color: #cccccc;
}

This has the added advantage of being extensible, so if you find yourself needing several selectors with really similar properties you can add in variables:

@mixin generic-hr($background-color: transparent) { 
  width: 100%;
  height: 1px;
  margin: 15px 0px; 
  background-color: $background-color;
}
.dark-hr {
  @include generic-hr(#595959);
}
.light-hr {
  @include generic-hr(#cccccc);
}
.medium-hr {
  @include generic-hr(#818181);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top