Skip to content

Instantly share code, notes, and snippets.

@robfletcher
Created May 17, 2013 08:45
Show Gist options
  • Select an option

  • Save robfletcher/5597817 to your computer and use it in GitHub Desktop.

Select an option

Save robfletcher/5597817 to your computer and use it in GitHub Desktop.
SASS mixin that uses modernizr to output fallback color property for browsers that don't support RGBA.
/*
* Outputs a color property with an opaque fallback for browsers that do not support RGBA.
*/
@mixin safe-rgba($property, $color, $fallback-color: opacify($color, 1)) {
@if opacity($color) == 1 {
#{$property}: $color;
} @else {
#{$property}: $fallback-color;
.rgba & {
#{$property}: $color;
}
}
}
@robfletcher

Copy link
Copy Markdown
Author

For example:

.foo {
    @include safe-rgba(background-color, rgba(255,255,255,0.5))
}

will output:

.foo {
    background-color: rgb(255,255,255);
}
.rgba .foo {
    background-color: rgba(255,255,255,0.5);
}

If the color you pass has no alpha opacity the .rgba block is omitted.

@twome

twome commented May 17, 2013

Copy link
Copy Markdown

Hey! I did a similar thing a short while ago, which lets you specify the colour of the backdrop behind your transparent foreground colour - ideally with a variable - so that Sass can use its mix function to get fake transparency. It looks identical to real transparency (for solid-on-solid colour). IE8 can use filter to get real background transparency, but if you use this you can also get "transparency" on border-color, font color, and everything else. It defaults to the most legitimate transparency available.

@mixin alpha-color($foreground, $backdrop: #fff, $property: 'background-color') {
    #{$property}: mix( fade-in($foreground, 1), $backdrop, percentage(opacity($foreground)) ); // Browsers without color opacity
    #{$property}: $foreground; // Decent browsers
    @if $property == 'background-color' {
        .lt-ie9 & { // IE8 has background filters; use them instead
            #{$property}: transparent;
            $ie-hex: ie-hex-str($foreground);
            filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#{$ie-hex},endColorstr=#{$ie-hex});
            zoom: 1;
        }
    }
}

Doesn't depend on Modernizr, but it does expect some kind of similar 'IE8' class in the <html> element, like H5BP's. Can Modernizr detect the old MS filters? Would be preferable to an IE8 class, but I don't think it can.

Might be helpful.

I took the filter idea taken from StackOverflow user "seutje" http://stackoverflow.com/a/8009864/1129420
http://caniuse.com/css3-colors

@robfletcher

Copy link
Copy Markdown
Author

That's great, much more thorough than my version. I don't think modernizr does have a detect for the on IE filters, no.

@twome

twome commented May 18, 2013

Copy link
Copy Markdown

Glad to help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment