Related Articles

Related Articles

Convert Hex to RGBa for background opacity using SASS
  • Last Updated : 19 Aug, 2020

Sass rgba function uses Red-green-blue-alpha model to describe colours where alpha is used to add opacity to the color. It’s value ranges between 0.0 (completely transparent) to 1.0 (completely opaque). The function takes two input values- the hex color code and alpha and converts Hex code to RGBa format.

Syntax:

  • Using background-color property:
    element {
        background-color: rgba(hex_value, opacity_value);
    }
  • Using mixins with background-color property that provides hex fallback:
    @mixin background-opacity($color, $opacity) {
        background: $color;  /*Fallback */
        background: rgba($color, $opacity);
    }
    
    body {
         @include background-opacity(hex_value, opacity_value);
    }

Below examples illustrate the above approach:

Example 1: Adding 70% opacity to a Hex code

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<head>
<title>Converting Hex to RGBA for background opacity</title>
</head>
<body>
  <p>GeeksforGeeks</p>
</body>
</html>

chevron_right


  • SASS code:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    @mixin background-opacity($color, $opacity) {
        background: $color;
        background: rgba($color, $opacity);
    }
      
    body {
         @include background-opacity(#32DF07, 0.7);
    }

    chevron_right

    
    

  • Converted CSS code:
    body {
      background: #32DF07;
      background: rgba(50, 223, 7, 0.7);
    }

Output:

Example 2: Adding 50% opacity to a Hex code

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
    <html>
     <head>
       <title>
Converting Hex to RGBA for background opacity
       </title>
     </head>
<body>
  <p>GeeksforGeeks</p>
</body>
</html>

chevron_right


  • SASS code:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    @mixin background-opacity($color, $opacity) {
        background: $color;
        background: rgba($color, $opacity);
    }
      
    body {
         @include background-opacity(#32DF07, 0.5);
    }

    chevron_right

    
    

  • Converted CSS code:
    body {
      background: #32DF07;
      background: rgba(50, 223, 7, 0.5);
    }

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :