oooyaya
oooyaya

Reputation: 1803

Additive properties in CSS

I know in vanilla CSS, there is no way to create "additive" properties. What I mean by that is:

.shade {
    background: rgba(0,0,0,.1);
}

<div class="shade">I have .1 black background</div>
<div class="shade shade shade">I also have .1 black background, but wouldn't it be cool if i had .3?</div>

What I hope to do is to avoid having to generate styles in a loop in order to multiply the opacity of a background shade and without having to specify a class for each one, because i don't know how many there are.

I suspect this isnt possible because it kind of defeats the purpose of the "C" in "CSS", and that's fine - but figured I'd ask in case somebody smarter than me knew of a way.

And I'd rather not do:

<div class="shade">
   <div class="shade">
     <div class="shade">
       No please
     </div>
   </div>
</div> 

Upvotes: 10

Views: 1278

Answers (1)

Itay Gal
Itay Gal

Reputation: 10824

You can do it with JQuery Working example

$("div").each(function(index){
    var classList = $(this).attr('class').split(/\s+/);
    var num = 0;
    $.each( classList, function(index, item){
        if (item === 'shade') {
            num = num + 0.1;
        }
    })
    $(this).css("background", "rgba(0,0,0," + num + ")");
 });

HTML:

<div class="shade">I have .1 black background</div>
<div class="shade shade other shade">I also have .1 black background, but wouldn't it be cool if i had .3?</div>
<div class="shade shade shade shade shade">0.5 opacity</div>

Upvotes: 3

Related Questions