This isn't a polyfill for RGBA in unsupported browsers but a fallback for use with progressive enhancement.

I still have to support older browsers at work in most projects (at the very least IE8) and so find myself having to often also create styles for features these don't support but overwritten by those that do, the progressive enhancement way.

One of these features is RGBA, this can be a bit of a nuisance as when providing a fallback you are actually wanting to provide a fallback for the resulting colour combining with the background because of the transparency rather than just the fully opaque version of the RGBA colour. This can be done through colour sampling the result in a browser that supports it and providing it as a hex, but that doesn't seem exactly efficient. I therefore wanted to create a mixin that would automatically compute the fallback colour for me.

The SASS @mixin

This mixin achieves this by taking the foreground colour and mixing it with the background colour in a particular ratio. It then using the same mixin parameters creates the correct RGBA style too. The mixin accepts the following parameters:

  • $color - Required
    Foreground color that are wanting to become semi-transparent and to which provide a hex fallback for.
  • $alpha - Optional
    Transparency amount of foreground color, as a percentage inc % unit. Defaults to 50%.
  • $bgcolor - Optional but highly recomended
    Color that appears behind the semi-transparent foreground color. Defaults to white.
  • $property - Optional
    Which CSS property the semi-transparent color is to be applied to. Defaults to background-color.
@mixin alpha($color, $alpha: 50%, $bgcolor: #fff, $property: background-color) {
  // Opacify any rgba value that may be passed through - just incase to avoid errors
  $color-hex: opacify($color, 1);
  $bgcolor-hex: opacify($bgcolor, 1);
  // Set max and min percentages to avoid errors
  @if $alpha > 100% { $alpha: 100%; }
  @if $alpha < 0% { $alpha: 0%; }
  // Creates decimal version of percentage value stripping unit and dividing by 100
  $decimal: ($alpha / ($alpha * 0 + 1) / 100);

  // Creates styles outputting: 
  // - Property Name - default background-color
  // - Fallback style with Hex value
  // - Proper style with RGBA value
  #{$property}: mix($color-hex,$bgcolor-hex, $alpha);
  #{$property}: rgba($color-hex, $decimal);

}

Usage

// Inputted SASS
.test-class {
  @include alpha($color: red, $alpha: 25%, $bgcolor: #aaa, $property: background-color);
}
// Outputted CSS
.test-class {
  background-color: #bf7f7f;
  background-color: rgba(255, 0, 0, 0.25);
}

See it in action

Click the button to toggle between the RGBA and Hex colour values. Inspect the code if you want to confirm that it's changing.

See the Pen Provide Fallback for RGBA values by Matthew Shields (@MatthewShields) on CodePen.