Shannon Hochkins
Shannon Hochkins

Reputation: 12175

SASS function for @extend

What I'm trying to achieve, is simply a shorter version of the @extend function in sass.

I have a heap of classes which I use all over my site for layout.

Example:

.grid1 {width:40px;}
.grid2 {width:80px;}
.grid3 {width:120px;}
.grid4 {width:160px;}
.grid5 {width:200px;}

I know you can use the extend function to remove duplicate css all over the site with:

.class {@extend .grid1}

which would output

.class {width:40px}

What I'm after is something a little more simple.

.class{grid(1)};

Here's what I've tried:

@function grid($n){
  @extend unquote(".grid#{$n}");
}

Obviously this doesn't work, any ideas?

Upvotes: 1

Views: 364

Answers (1)

Jonas G. Drange
Jonas G. Drange

Reputation: 8845

@functions in SASS are meant to be used to manipulate values. So the reason why this will not work is due to the fact that you are trying to return selectors and declaration blocks. This is what mixins are for.

One way of doing this would be:

$grids: ((5, 40), (10, 80), (15, 120), (20, 160));

@mixin grid($n, $fluid: false) {
    @if($fluid) {
        width: nth(nth($grids, $n), 1) + "%";
    } @else {
        width: nth(nth($grids, $n), 2) + "px";
    }
}

.foo {
  @include grid(3);
}

.bar {
   @include grid(4, true);
}

Which produces:

.foo {
  width: "120px"; }

.bar {
  width: "20%"; }

Upvotes: 4

Related Questions