Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit color but override opacity/transparency

Tags:

html

css

Is it possible to inherit the color but override the opacity value? Here's an example in pseudo CSS:

.color-class {
    background-color: rgba(255, 0, 0, 0);
}

.lighten {
    background-color: rgba(inherit, inherit, inherit, .4);
}

Applied to

<div style="color-class">I am red</div>
<div style="color-class lighten">
    I am red and a little bit transparent
</div>

should result in a colored element and the other one being the same (inherited) color but with added transparency.

I basically want to have a CSS class that lightens (or darkens) the background color without changing the color value.

like image 229
twigmac Avatar asked Dec 15 '17 11:12

twigmac


People also ask

Is opacity inherited?

Opacity is not inherited, but because the parent has opacity that applies to everything within it. You cannot make a child element less transparent than the parent, without some trickery. Values are a number from 0 to 1 representing the opacity of the channel (the “alpha” channel).

How do you change opacity without affecting children's elements?

Answer: Use the CSS RGBA colors There is no CSS property like "background-opacity" that you can use only for changing the opacity or transparency of an element's background without affecting its child elements.


Video Answer


2 Answers

Firstly, this would not work because inherit takes the value from an elements parent element not its sibling element. See: https://developer.mozilla.org/en-US/docs/Web/CSS/inherit

Secondly, the inherit keyword is a property-value. It cannot be used as an argument to a browser function (rgba) as the function itself is a property-value.

You also don't need to try this hard to enforce inheritance and re-usability, it will often bloat your code and make it over-engineered.

You would ideally have a set colour scheme and therefore be able to choose a fixed colour for lighten, considering you would be re-using this there isn't that much need to try and make it dynamic like that.

Other options you can go for if you REALLY want this functionality are using SASS/SCSS mix-ins to mimic this inheritance, JavaScript could also be an alternative however for what you're trying to achieve this would be really in-efficient.

like image 114
Felipe Warrener-Iglesias Avatar answered Oct 03 '22 06:10

Felipe Warrener-Iglesias


A solution is to use pseudo element as background and simply control its opacity :

div {
  padding: 40px;
}

.color-class {
  position: relative;
}

.color-class:before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgb(255, 0, 0);
  opacity: 1;
  z-index:-1;
}

.lighten:before {
  opacity: 0.5;
}
<div class="color-class">I am red</div>
<div class="color-class lighten">
  I am red and a little bit transparent
</div>
like image 31
Temani Afif Avatar answered Oct 03 '22 06:10

Temani Afif