0

I want to change only the opacity of existing background color , the color is controlled by server and i can't change it because i use a website builder , but i want to override the background opacity value with style="" .
I've read How do I give text or an image a transparent background using CSS? and also searched through internet and the only answer i found was to use rgba(r,g,b,a) function .

So how do i make it so that the r,g,b inherit from previous value except for the alpha (opacity) ? if not possible , any workaround to achieve the same thing ? And if pure css solution is not possible , any workaround using javascript ?

1 Answers1

1

There is a way to achieve this in JavaScript:

  1. First, target your element:

    var elem = document.querySelector('#maincontent');

  2. Then, you can capture the current background-color:

    var oldColor = getComputedStyle(elem ).backgroundColor;

  3. Then, update the color:

    var newColor = 'rgba' + oldColor.slice(3, -1) + ', 0.5)';

    // The above line will convert the color from rgb to rgba

    // rgb(16, 14, 23) => rgba(16, 14, 23, 0.5)

  4. Now, you can update the bg-color of the target element:

    elem.style.backgroundColor = newColor;

Shuvo
  • 1,253
  • 9
  • 18
  • yo this is actually clever working workaround , especially the slice part , but can you please do it without cropping string ? performance issue reason .... (upvoted anyway thanks :D) – i'm ashamed with what i asked Oct 31 '20 at 05:37
  • Since you need the original `rgb` color code, you actually need to slice the string. There should be a better way to retrieve the color code, but I don't think you can do it without slicing. And, by the way, I think this small string slicing operation won't cause any performance issue – Shuvo Oct 31 '20 at 05:46
  • Well if it's not possible then okay , just a little more careful to optimization won't hurt . Small slicing isn't performance issue but multiply that by hundreds elements and the effect start to take place . – i'm ashamed with what i asked Oct 31 '20 at 06:02