Stylus gets @extend

@extend is a great little feature which originated in SASS, and now finds a home in Stylus. If you’ve ever written CSS like this, you know it can become quite the pain to maintain large lists of selectors:

.message,
.warning,
.error {
  font-size: 14px;
  padding: 5px 10px;
  border: 1px solid #eee;
  border-radius: 5px;
}

.warning {
  color: yellow;
}

.error {
  color: red;
}

@extend makes this process flow naturally, and even supports inheritance. In Stylus you may use @extend or @extends, I prefer the latter personally but that’s up to you! Using this feature you would define .message on it’s own, and simply __@extend_ it from within the other rulesets:

.message {
  font-size: 14px;
  padding: 5px 10px;
  border: 1px solid #eee;
  border-radius: 5px;
}

.warning {
  @extends .message;
  color: yellow;
}

.error {
  @extends .message;
  color: red;
}

Taking this even further with inheritance:

.fatal-error {
  @extends .error;
  font-weight: bold
}

Would yield the following CSS:

.message,
.warning,
.error,
.fatal-error {
  font-size: 14px;
  padding: 5px 10px;
  border: 1px solid #eee;
  border-radius: 5px;
}
.warning {
  color: #ff0;
}
.error,
.fatal-error {
  color: #f00;
}
.fatal-error {
  font-weight: bold;
}

Here’s another example:

form
  button
    padding: 10px
    border: 1px solid #eee
    border-radius: 5px

ul
  li a
    @extends form button

Yielding:

form button,
ul li a {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 5px;
}

And of course you may utilize the alternative Stylus syntax if you prefer:

.message
  font-size: 14px
  padding: 5px 10px
  border: 1px solid #eee
  border-radius: 5px

.warning
  @extends .message
  color: yellow

.error
  @extends .message
  color: red

.fatal-error
  @extends .error
  font-weight: bold

Grab Stylus 0.22.4 for these goodies!

Notes

  1. sveisvei reblogged this from tjholowaychuk
  2. tjholowaychuk posted this