Wrights HQ

A blog by Ian Wright - Front-end web developer

For my work I am developing more mobile & retina websites. To make life easier when writing CSS we should all be using SASS. Below is a great mixin for SVG (Scalable Vector Graphics) with PNG fallback for older browsers (IE8 & below)

Example One:

This example loads in the SVG graphic but for older browsers will fallback to a PNG.

@mixin svg-bg($name) {
  background-image: url('../images/css/#{$name}.png') transparent 0 0 no-repeat; // IE8 & below
  background-image: none, url('../images/css/#{$name}.svg') 0 0 no-repeat;
}

Example Two:

This example we can pass in addition parameters to control the fallback extensionbackground colourposition & repeat.

@mixin svg-bg($name, $extension: png, $color: transparent, $position: 0 0, $repeat: no-repeat) {
  background: url(../images/css/#{$name}.#{$extension}) $color $position $repeat;
  background: none, url(../images/css/#{$name}.svg) $color $position $repeat;
}

As a Sass mixin is a function we can then include it within any of our class styles.

Example One:

.background {
  // File name only
  @include svg-bg('graphic-name');
}

Example Two:

.background {
  /*
   * Here we can pass parameters: name, extension, color, position, repeat
   * with this example we will just repeat the graphic
   */
  @include svg-bg('graphic-name', $repeat: repeat);
}