Skip to content

Instantly share code, notes, and snippets.

@ry5n
Created December 12, 2011 01:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ry5n/1464180 to your computer and use it in GitHub Desktop.
Save ry5n/1464180 to your computer and use it in GitHub Desktop.
Using Sass lists for DRY-er code
// Shared colors for buttons and alerts
//
// Use Sass lists to avoid writing out repeating patterns of Sass code.
//
// For example, the following avoids having to write out a selector and
// set of style rules for each alert type, when only class and
// variable names are different.
//
// Follows (and many thanks to) Nathan Weizenbaum (@nex3)’s comment at:
// http://groups.google.com/group/sass-lang/msg/987926ad9fe5ad43?
//
// @note $info-color, $success-color, etc. are assumed to be assigned elsewhere.
//
// @note The background-image and linear-gradient functions are part of the
// Compass framework http://compass-style.org
.button,
.alert-message {
@each $alert-type in (
info $info-color,
success $success-color,
warning $warning-color,
error $error-color,
danger $danger-color
) {
&.#{nth($alert-type, 1)} {
color: white;
background-color: nth($alert-type, 2);
@include background-image(
linear-gradient( rgba(black, 0), rgba(black, .05) )
);
}
}
}
@ry5n
Copy link
Author

ry5n commented Dec 12, 2011

The equivalent, repetitious Scss without using list functions would be:

.button,
.alert-message {
  &.info {
    color: white;
    background-color: $info-color;
    @include background-image( linear-gradient( rgba(black, 0), rgba(black, .05) ) );
  }
  
  &.success {
    color: white;
    background-color: $success-color;
    @include background-image( linear-gradient( rgba(black, 0), rgba(black, .05) ) );
  }

  &.warning {
    color: white;
    background-color: $warning-color;
    @include background-image( linear-gradient( rgba(black, 0), rgba(black, .05) ) );
  }
  
  &.error {
    color: white;
    background-color: $error-color;
    @include background-image( linear-gradient( rgba(black, 0), rgba(black, .05) ) );
  }
  
  &.danger {
    color: white;
    background-color: $danger-color;
    @include background-image( linear-gradient( rgba(black, 0), rgba(black, .05) ) );
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment