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.
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).
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With