1

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.

Matt Stow
  • 6,053
  • 6
  • 24
  • 26
  • 2
    If the solution you're looking for is in Compass, it seems illogical to not use Compass. – cimmanon May 01 '13 at 12:12
  • @cimmanon Compass & CompassApp are really bad on Windows, constantly locking the files so I can't edit. Also, Compass produces bad SVG in that it puts it on the background property, which blows away IE8 & 7's fallback background – Matt Stow May 01 '13 at 22:24
  • Oh, and it doesn't use the correct W3C gradient syntax – Matt Stow May 01 '13 at 22:57
  • So don't use it on Windows? Use the `background-image` mixin, not the `background` mixin (see: http://compass-style.org/examples/compass/css3/gradient/). Gradient syntax is fixed in the gradients branch (see: https://github.com/chriseppstein/compass/issues/965) – cimmanon May 01 '13 at 23:59

1 Answers1

1

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 + '" />';
        }
    }
Matt Stow
  • 6,053
  • 6
  • 24
  • 26