Pregunta

Estoy tratando de limpiar mi CSS para que esté más limpia utilizando SCSS.

CSS estándar:

.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;
}

¿Hay alguna manera de evitar la creación de la clase 'Genic-HR' que no se utilizará? Esperaba que algún tipo de nido funcione bien. En este escenario, el CSS es definitivamente un limpiador y más legible que SCSS.

Idealmente, necesitaría esto para trabajar en SCSS:

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

PRODUCCIÓN:

 .dark-hr, .light-hr {
   //shared attributes defined by '.##'
 }
 .dark-hr {
   // overrides
 }
 .light-hr {
   // overrides
 }
¿Fue útil?

Solución

Lo que quieres usar es un extensión de clase (Los llamo "clases silenciosas"), que está significada mediante el uso de un % en lugar de un ..

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;
}

Otros consejos

¿Normalmente lo harías algo así:

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

Mi patrón para este tipo de cosas es una mezcla:

@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;
}

Esto tiene la ventaja adicional de ser extensible, por lo que si se encuentra que necesita varios selectores con propiedades realmente similares, puede agregar 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);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top