Use dynamic SASS function names inside a loop

186
January 16, 2018, at 4:27 PM

I am creating some utility classes via a loop but wan't to use the functions that already exist.

I have some functions that I use within other CSS:

@function size-1() {
    @return  #{ ( 8 / 16 ) }rem;
}
@function size-2() {
    @return #{ ( 16 / 16 ) }rem;
}
@function size-3() {
    @return #{ ( 24 / 16 ) }rem;
}
@function size-4() {
    @return #{ ( 32 / 16 ) }rem;
}

But I also created a loop so that I have classes to use in the markup too:

@for $i from 1 through 18 {
    .mt-#{$i} {
        margin-top: size-$i();
    }
}

I have tried (above) to dynamically call the function but it only outputs text of 'size-1' if I do it dynamically. If I use the direct function name e.g.:

margin-top: size-1();

Then it correctly works. Is there any way I can do this?

Answer 1

Use the function call to call yours:

@function size-1() {
    @return  #{ ( 8 / 16 ) }rem;
}
@function size-2() {
    @return #{ ( 16 / 16 ) }rem;
}
@function size-3() {
    @return #{ ( 24 / 16 ) }rem;
}
@function size-4() {
    @return #{ ( 32 / 16 ) }rem;
}
...
@for $i from 1 through 18 {
    .mt-#{$i} {
        margin-top: call(size- + $i);
    }
}

Tried in: https://www.sassmeister.com/

Rent Charter Buses Company
READ ALSO
CSS - input:invalid not

CSS - input:invalid not

I'm having a validation problem

251
cannot run project in server [on hold]

cannot run project in server [on hold]

When i am running project in localhost it is working fine, while running in my server i am getting following error

163