Matt Stow
Matt Stow

Reputation: 6379

Sass - Nested @each loop and nth to grab separate values

I'm trying to write a CSS3 gradient mixin that also produces SVG for IE9.

I want to pass in a large string (a list) of the nodes' colours and positions which are comma separated but also split these groups in to individual values for relevant SVG attributes.

So, given a value of: #000 0%, #333 33%, #555 50%, #666 66%, #FFF 100%

and this simplified mixin:

@mixin gradient($direction, $nodes) {
    $css: '';
    $svg: '';

    @each $node in $nodes {
        $css: $css + ', ' + $node;
    }

    $css: $direction + $css;
    $css: unquote($css);
    background-image: linear-gradient($css);
}

How can I separate $node to produce a required amount of SVG tags (pseudo-code):

$svg: $svg + '<stop stop-color="nth($node, 1)" offset="strip-units(nth($node, 2))/100" />';

To produce:

<stop stop-color="#000" offset="0" />
<stop stop-color="#333" offset="0.33" />
<stop stop-color="#555" offset="0.5" />
<stop stop-color="#666" offset="0.66" />
<stop stop-color="#fff" offset="1" />

I tried using a second @each inside the first loop, but that didn't seem to do much.

Any help is greatly appreciated.

And no, I don't want to use Compass's CSS3 gradient features.

Upvotes: 1

Views: 1528

Answers (1)

Matt Stow
Matt Stow

Reputation: 6379

I changed the input slightly and used a @for loop to achieve what I want.

The value now comma separates everything:

$nodes: #000, 0%, #333, 33%, #555, 50%, #666, 66%, #FFF, 100%

And the @for loop looks like this:

@for $i from 0 to length($nodes) {
        @if ($i % 2 == 0) {
            $css: $css + ", " + nth($nodes, ($i + 1));
            $svg-nodes: $svg-nodes + '<stop stop-color="' + nth($nodes, ($i + 1)) + '"';
        }
        @else {
            $css: $css + " " + nth($nodes, ($i + 1));
            $svg-nodes: $svg-nodes + ' offset="' + strip-units(nth($nodes, ($i + 1)))/100 + '" />';
        }
    }

Upvotes: 1

Related Questions