Exploring the power of transparency using sass and css variables

I have been loading CSS variables into my application from a database using a custom function. The code looks something like this:

document.documentElement.style.setProperty(--primaryColor,'#56647B');

Everything seems to be working fine except when I try to add opacity to my color.

background-color: rgba($primaryColor, 0.15)
is not functioning as expected. When I check the console, I see
background-color: rgba(var(--primaryColor, #56647B), 0.15);

There are no errors in the code, but this background color just won't work with opacity added. Any suggestions? It appears that Sass is having trouble processing the var.

Thank you for any assistance.

I have attempted to use CSS variables with Sass, but I am currently searching for a workaround or a method to allow Sass to process CSS variables and work correctly with opacity on components.

Answer №1

If you're still looking for a solution, here are some alternatives and workarounds since it's not achievable out of the box. You can convert the colors to either rgb/a or hsl/a.

rgb() or rgba() require 3 or 4 arguments (r, g, b, a), so they cannot interpret #56647B. The same applies to hsl() and hsla().

SASS provides the built-in function rgba() which can handle hex values. For example, in SASS:

.my-class {
    background-color: rgba(#123456, 0.5);
}

will be compiled as:

.my-class {
  background-color: rgba(18, 52, 86, 0.5);
}

Another option is to set the colors on :root using:

$yourColorHex: #56647B;
--my-color-with-alpha: rgba($yourColorHex, 0.15);

// basic hex to rgb converter
function hexToRGB(hex) {
  const hexNormalized = hex.replace('#', '');
  const red = parseInt(hexNormalized.substr(0, 2), 16);
  const green = parseInt(hexNormalized.substr(2, 2), 16);
  const blue = parseInt(hexNormalized.substr(4, 2), 16);
  return `${red}, ${green}, ${blue}`;
}

// handling rgb and rgba values
function hexToRGBA(hex) {
  const hexNormalized = hex.replace('#', '');
  const red = parseInt(hexNormalized.substr(0, 2), 16);
  const green = parseInt(hexNormalized.substr(2, 2), 16);
  const blue = parseInt(hexNormalized.substr(4, 2), 16);
  const alpha = hexNormalized.substr(6, 2);
  let alphaPercentage = '100';
  if (!!alpha) {
    alphaPercentage = Math.round(parseInt(alpha, 16) / 0xFF * 100);
  }
  return `${red}, ${green}, ${blue}, ${alphaPercentage}%`;
}

// apply an alpha channel to your hex value
function hexWithAlpha(hex, alpha) {
  const hexNormalized = hex.replace('#', '');
  const alphaHex = Math.round(alpha * 0xFF).toString(16);
  return `#${hexNormalized}${alphaHex}`;
}

// manually convert your hex into an RGB value and separate the values in the css property e.g. #56647B = rgb(86, 100, 123)
document.documentElement.style.setProperty('--col1', '86, 100, 123');

// add an alpha channel to your hex-value manually
// #56647B26 = rgba(86, 100, 123, 0.15);
// https://gist.github.com/lopspower/03fb1cc0ac9f32ef38f4
// https://caniuse.com/css-rrggbbaa
document.documentElement.style.setProperty('--col2', '#56647B26');

// convert hex to rgb with a helper function
document.documentElement.style.setProperty('--col3', hexToRGB('#56647B'));

// convert hex to rgba with a helper function
document.documentElement.style.setProperty('--col4', hexToRGBA('#56647B26'));

// add an alpha channel to your hex-value with a helper function
document.documentElement.style.setProperty('--col5', hexWithAlpha('#56647B', 0.15));
:root {
  --col1: hotpink;
  --col2: hotpink;
  --col3: hotpink;
  --col4: hotpink;
  --col5: hotpink;
}

.container {
  display: flex;
  flex-flow: row nowrap;
  gap: 15px;
}

.box {
  width: 100px;
  height: 100px;
}

.box-1 {
  background-color: rgba(var(--col1), 0.15);
}

.box-2 {
  background-color: var(--col2);
}

.box-3 {
  background-color: rgba(var(--col3), 0.15);
}

.box-4 {
  background-color: rgba(var(--col4));
}

.box-5 {
  background-color: var(--col5);
}
<div class="container">
  <div class="box box-1">Box 1</div>
  <div class="box box-2">Box 2</div>
  <div class="box box-3">Box 3</div>
  <div class="box box-4">Box 4</div>
  <div class="box box-5">Box 5</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the function of mdLiveAnnouncer in Angular Material and how it operates?

Could someone provide an explanation of $mdLiveAnnouncer using this code snippet? module.controller('AppCtrl', function($mdLiveAnnouncer) { // Making a basic announcement (Polite Mode) $mdLiveAnnouncer.announce('Hey Google'); // ...

Shift designated list item to the right with overflow handling

A current project involves working on a sidebar created in bootstrap, and I've encountered an issue. I can't seem to move a selected item to the right and have it flow over the nav div. I attempted to increase the z-index with no success. One su ...

Arrange various numbers in a single row to be in line with

I'm utilizing bootstrap in an attempt to design the layout depicted below: https://i.sstatic.net/0w06U.png Here is a simplified version of my code: .curr { font-size: 12px; font-weight: 700; letter-spacing: .5px; } .price { -webkit-tap-h ...

Arranging images in layers using jQuery or CSS

My current challenge involves two overlapping images. I am looking for a solution where clicking on the back image will bring it forward. I prefer a simple method that is also mobile-friendly since I am using Bootstrap for responsiveness. What suggestions ...

Rotating elements in CSS using the transform property with rotateX and rotateY values

I've created a transformation effect using CSS, and now I'm looking to start with a specific rotation (rotateX(15deg) rotateY(180deg)) and then animate it back to its original position. Is there a way to achieve this reversal effect and how can i ...

Resizing a floated div causes the image to break out

My webpage has a container div with two floated left divs inside, positioned side by side. The right div contains a YouTube video and an image. However, when I resize the page, the video and picture flow out of the containing floated div instead of dropp ...

How can I prevent tinymce from stripping out my <link> tag?

I'm having an issue with tinymce. dd<script id="kot-id" src="***insert link here***"></script><div id="kotcalculator"></div><link rel="stylesheet" href="***insert link here***" type="text/css" media="screen" /> It seems ...

Font transparency is not displaying properly

I am attempting to adjust the opacity of text displayed on a d3 pie chart, but I'm facing issues where only the fill is rendering correctly and not the opacity. Below is the code snippet where I am trying to apply opacity: var txts = svg.data([json ...

Learn how to collapse a list by clicking outside of it on the document with the following code: $(document).on("click"

I want to create a collapsible/expandable menu for my website. I had a version where hovering over a category would expand the subcategory, but what I really need is for the subcategories to expand when I click on a category and remain expanded until I cli ...

Unable to adjust SVG fill color

I'm having trouble changing the fill color of an SVG when the user hovers over it. Can someone help me figure out why my code isn't working? svg:hover { fill: blue; } <svg width="0" height="0" class="hidden"> <symbol viewBox="0 0 ...

Icons on Google Calendar events - Mini images beside your schedule

I'm in the process of developing a website where I plan to integrate Google Calendar. I want to include a small icon next to specific events to denote certain details. While the "categories" feature in Google Calendar allows me to assign highlight col ...

Is there a way for me to incorporate a feature that lets the user specify the URL based on their input in a search box?

Currently, I am working on a project that involves creating two text fields for user input, along with a "View Report" button. My goal is to have the button redirect users to a specific URL structured like this: http://example.com/reports/example/reports/ ...

Arrange elements in different directions to accommodate smaller screens

I need help aligning my brand and the links on opposite sides (brand on left, other links on the right) for mobile view. The issue I'm facing is that the links on the right end up moving to the next line. Any suggestions or advice would be greatly app ...

Set the clock to the correct time by winding it up

I have created a vintage-inspired clock using javascript and css. function updateClock() { var now = moment(), second = now.seconds() * 6, minute = now.minutes() * 6, hour = now.hours() % 12 / 12 * 360 + 90 + minute / 12; ...

Creating a custom filter

I am working on creating a filter and I could use some assistance with making minimal changes to my code. I am confident that there is a practical solution for what I am trying to achieve and would appreciate any corrections or suggestions. Button01' ...

Tips for customizing Bootstrap theme color schemes in a React/Redux application that has been bootstrapped

As a newcomer to REACT, I am facing an issue with changing the theme colors in my freshly bootstrapped react application. I have gone through some solutions suggested by others but none of them seem to work for me. My entry point looks like this: import ...

Ways to conceal overflow at the base of a container while enabling the image to break free from the top of the container

Trying to create a visual effect where an image of a person appears to be partially hidden inside a container, with the bottom part concealed by overflow: hidden. However, I want the top part of the image to extend out of the container. Is there a way to a ...

What is the best way to format each <li> element onto a separate line?

Creating a review section for an item on my website required me to organize the reviews and comments. I utilized the following code structure: <ul> <li> Comment code </li> <li> Comment code </li> </ul> Within the ...

Challenges encountered while adjusting the dimensions of the Bootstrap carousel

Earlier on, I delved into using Bootstrap for the first time and encountered some difficulties with resizing a carousel on one of my pages. This specific page had a gradient background in the body and an overlay bg in the content section. In attempting to ...

Maintain the aspect ratio of DIV or image

I am looking to maintain the aspect ratio of a DIV element, similar to how it's done on Google Maps. <div id="map" style="background-color: grey;width:100%;"> Map here </div> The current setup adjusts the width based on the window size o ...