Search code examples
javascriptcssbackground-coloropacityrgba

CSS inherit previous background rgba value EXCEPT alpha (opacity)


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 ?


Solution

  • 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;