0

I'm currently building a web app in Angular, and have stumbled onto some very odd differences in the final color that is being outputted. The premise is this:

I have a global color variable in :host of app.component.scss --primary-color-in-host: rgba(38, 50, 56, 0.9)

I want to use this color variable across my app in various components, and able to do so successfully using: var(--primary-color-in-host).

No problem there. However, I would also like to occasionally apply an opacity to this color. This is where the problem appears.

Normally, if you declare a variable locally in the component's scss $primary-color-local: rgba(38, 50, 56, 0.9), you can successfully apply opacity to the variable like so: color:rgba($primary-color-local, .5). But because I've declared the variable globally in :host(see above), the opacity does not apply when I try to apply it using rgba(var(--primary-color-in-host), .5). I just get the color, but not the opacity!

Naturally, I could just re-declare this color in each component's .scss, but would like to avoid doing so (for obvious reasons). But before I can even begin to tackle the problem, I need to understand what is going on underneath the surface. Why is it working locally, but not when the color is being pulled from :host?

1 Answers1

0

I have a global variable in :host

Did you mean :root, or the template's :host?

Anyway, it works 'locally' because you're saving the color as a SASS variable, which allows the (SASS) parser to replace it with the actual value and then try to figure out what exactly you want before transpiling your document, and maybe fix some mistakes.

SASS doesn't touch native CSS variables, those are computed dynamically at runtime. The browser engine has no idea what you're trying to do when it computes your custom property to rgba(rgba(38, 50, 56, 0.9), .5).

This answer goes into more detail and how you might solve it.

eMontielG
  • 396
  • 1
  • 7
  • :host in app.component.scss. I've looked at that answer. That's where I learned how to apply opacity in the first place. The problem isn't that I can't apply opacity. I've already solved that. The issue is that I can't do the same thing with a global variable what I have already done with a local one. – King Arthur the Third Mar 04 '20 at 00:01
  • Yes, because you're declaring your local variable as a SASS variable. At least that's how you're doing it in your example. The SASS parser will look at your code and see that you're nesting an rgba() rule inside another and fix that. SASS doesn't touch CSS custom properties, and the browser engine will compute them as is. – eMontielG Mar 04 '20 at 00:07
  • I've tested rgba(rgba(38, 50, 56, 0.9), .5). It actually works. The parser **is** able to figure out what I want from it. So I'm not quite sure what you're getting at... – King Arthur the Third Mar 04 '20 at 00:08
  • Test it again without using SASS. – eMontielG Mar 04 '20 at 00:23