Sass mixin for background transparency back to IE8

前端 未结 3 1599
刺人心
刺人心 2021-01-30 18:15

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 becau

3条回答
  •  梦毁少年i
    2021-01-30 18:47

    This probably is as bulletproof as you'll get without a proper shim.

    To build on seutje's answer, this lets you use ms-filter transparency if you're doing background-color on IE, but if you if you know the colour of the element behind the element you want to make transparent, you can use Sass's "mix" function to mix the two colours and get fake transparency - for any kind of colour. That means borders and text and all that jive. It's still a manual fallback but it'll give you the exact colour you're trying to simulate with a solid hex.

    SCSS:

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

    To get border-color: rgba(255, 0, 0, 0.5) on a blue background, you'd use it like:

    .blue-container {
        $color-bg: rgb(0,0,255);
        background-color: $color-bg;
        .transparent-red-element {
            @include alpha-color(rgba(255, 0, 0, .65), border-color, $color-bg);
        }
    }
    

    Sass automatically turns 100% opacity colors back into a hex code, hence the fade-in of 100%.

    The only browsers without colour opacity are IE8 <=8 and Opera <=9.6, and IE 8 has filters so this only helps for colors other than background-color. The principle is that you mix the background and foreground colours together into a flat hex.

    ie-hex-str is like a year old now so you'll definitely have it.

提交回复
热议问题