Skip to content
Related Articles
Open in App
Not now

Related Articles

Convert Hex to RGBa for background opacity using SASS

Improve Article
Save Article
  • Last Updated : 19 Aug, 2020
Improve Article
Save Article

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




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

  • SASS code:




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

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

Output:

Example 2: Adding 50% opacity to a Hex code




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

  • SASS code:




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

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

Output:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!