Joe Joe - 4 months ago 7
CSS Question

Is there a way to shorten this css using Sass?

Is there a way to shorten this code and reuse the two lines that are repeating - first and third? I have tried with @extend(adding .gradient class to my html, and after that a .gradient--1 etc.) but it does not work as supposed, nor does nesting. I have tried a mixin as well but can't figure out how to 'save' two properties inside it. Here's my css:

.gradient--1 {
padding-left:20px;
background:linear-gradient($gradient1, $gradient1a) no-repeat bottom left;
background-size:5px calc(100% + 1em);
}

.gradient--2 {
padding-left:20px;
background:linear-gradient($gradient2, $gradient2a) no-repeat bottom left;
background-size:5px calc(100% + 1em);
}

.gradient--3 {
padding-left:20px;
background:linear-gradient($gradient3, $gradient3a) no-repeat bottom left;
background-size:5px calc(100% + 1em);
}

.gradient--4 {
padding-left:20px;
background:linear-gradient($gradient4, $gradient4a) no-repeat bottom left;
background-size:5px calc(100% + 1em);
}

.gradient--5 {
padding-left:20px;
background:linear-gradient($gradient5, $gradient5a) no-repeat bottom left;
background-size:5px calc(100% + 1em);
}

Answer

A mixin is a reusable block of style rules. You can use parameters to describe how arguments may be used, and then - when you include it, pass arguments to it / as many as you want. There are also ways to set defaults and stuff / but admittedly, I find the docs to be confusing.

@mixin special-gradient($a, $b) {
  padding-left:20px;
  background:linear-gradient($a, $b) no-repeat bottom left;
  background-size:5px calc(100% + 1em);

.gradient--1 {
  @include special-gradient(red, blue);
}

.gradient--2 {
  @include special-gradient(green, blue);
}

...

or, you could use extend to extend a class

.setup-class {
  padding-left:20px;
  background-size:5px calc(100% + 1em);
}

.gradient--1 {
  @extend .setup-class;
  background:linear-gradient(red, blu) no-repeat bottom left;
}

.gradient--2 {
  @extend .setup-class;
  background:linear-gradient(red, blu) no-repeat bottom left;
}

...

Or do a combination of both. Look at the output file though... and see what really happens in each scenario ~ so you can see how your CSS is actually coming out the other end.

http://sass-lang.com/guide#topic-6

compare stylus for fun...

special-gradient($a, $b)
  background: linear-gradient($a, $b) no-repeat bottom left

.gradient-1
  special-gradient(red, blue)