Sass mixin for background transparency back to IE8

RSG picture RSG · Aug 1, 2011 · Viewed 14k times · Source

I'm new to Sass and struggling with this. I can't get the color to render in both hex (for IE) and rgba. Every little piece is frustrating me because I haven't mastered the syntax yet, and Google results for Sass are still sparse.

Here's the mixin:

@mixin transparent($hex, $a){
    /* for IEGR8 */
    background: transparent;
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#{$a}#{$hex},endColorstr=#{$a}#{$hex});
    zoom: 1;
    /* for modern browsers */
    background-color: rgba(#{$hex},.#{$a});
}

Such that @include transparent(#FFF,.4) should produce the nice, browser compatible transparent code below:

background: transparent;         
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#40FFFFFF,endColorstr=#40FFFFFF);
zoom: 1;
background-color: rgba(100,100,100,.40);

I've been noobing on the following for a couple hours:

  • The # required for #RGB format.
  • The . required for rgba alpha.

Both need to be included for the call to rgba(), however the # can't be included for the IE #AARRGGBB or it will look like #AA#RRGGBB, and the . can't be included for IE or it rejects #.AARRGGBB.

Am I missing a much simpler way to do this? Can this be done with Sass string manipulation or any slightly clever color cast function in Sass which handles this for me already?

Answer

seutje picture seutje · Nov 4, 2011
@mixin transparent($color, $alpha) {
  $rgba: rgba($color, $alpha);
  $ie-hex-str: ie-hex-str($rgba);
  background-color: transparent;
  background-color: $rgba;
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#{$ie-hex-str},endColorstr=#{$ie-hex-str});
  zoom: 1;
}

NOTE: The ie-hex-str is only available in recent versions, not sure when it was introduced though