Background Opacity No RGBA for Sass

17,598

Solution 1

You can use Sass functions to add transparency to a color.

background: rgba($dark, 0.5);    

or

background: transparentize($dark, 0.5);

or

background: fade-out($dark, 0.5);    

Sass has lots of handy functions for manipulating colors, strings, numbers, selectors, and more.

Solution 2

Makes not much sense to not use rgba.

Both opacity and rgba() are not supported by IE8, just 9 and above (if you are required to support it). With the exception that IE8 accepts the filter, that can be somewhat of a workaround to transparency.

If that isn't the case, and you simply don't want to use because it's annoying to convert hex to rgb, (which I too find annoying), no fear! SASS accepts a HEX #000 as a value for rgba and converts it properly, like this:

$dark: #000;
background-color: rgba($dark, .5); //outputs background-color: rgba(0,0,0,.5); in this case

But anyways, here is an approach with pseudo-elements after/before (you choose). Refer to the comments:

$dark: #000;
$highlight: blue;

nav {
    width:100%;
    background-color: transparent; //transparent or you won't see the color behind!

    //needs to be relative or after will go outside nav bounds
    position: relative;
    z-index: 0;

    //using after (or before) to fake the bg
    &::after { //if you need to support IE8, use single colon instead. Standard is :: but IE8 just supports with one
        content:"";
        display: block;


        //those two really could be just be
        //"background-color: rgba($dark, .5);" you know
        background: $dark; 
        opacity: .5;
        //filter here if you want IE8 support

        //making it fill entire nav
        bottom: 0;
        top: 0;
        left: 0;
        right: 0;
        position: absolute;

        //behind our nav
        z-index: -1;
    }
    //ul and so on here
}
Share:
17,598
noelietrex
Author by

noelietrex

I'm a front-end developer working primarily with html, css, and scss. I also work with javascript, jquery and coldfusion regularly.

Updated on June 04, 2022

Comments

  • noelietrex
    noelietrex almost 2 years

    Is there a way to make my background transparent without using RGBA so that I can change the color using Sass variables later without making the contained text transparent?

    $dark: #000;
    $highlight: blue;
    
    nav {
        width:100%;
        background: $dark;
        opacity: .5;
        ul {
            li {
                margin: 0 3%;
                a {
                    display: block;
                    font-size: 1.4em;
                    &:hover {
                        color:$highlight;
                    }
                }
            }
        }
    }