Is it possible to mix transparent and solid colors in CSS3?

Is it possible to dynamically make a transparent background from a solid and transparent color in CSS3? For instance:

<div class="red trans1"> CONTENT </div> 

with CSS

 .red { background: #FF0000; } .trans1 background: rgba(255,255,255,0.5); } 

In this case, the solid color completely covers the transparency. Of course, I mean using different properties ( background , background-color , etc.).

I have 10 solid colors and you want to create 10 levels of transparency for each. If you individually make a transparent color for each color, it needs 100 CSS classes; eg:.

 .red1 { .background: rgba(255,0,0,0.1); } .red2 { .background: rgba(255,0,0,0.2); } .red3 { .background: rgba(255,0,0,0.3); } .... .blue1 { .background: rgba(0,0,255,0.1); } .blue2 { .background: rgba(0,0,255,0.2); } .blue3 { .background: rgba(0,0,255,0.3); } 

I am looking for a dynamic way to mix solid color and transparent background.

+6
source share
2 answers

Pure CSS

Yes, you can turn off color and transparency by creatively using pseudo-elements. For example, this fiddle demonstrates the following code (note that I arranged everything based on the pseudo-element :after ):

HTML

 <div class="opBkg red op10">Red 10%</div> <div class="opBkg red op50">Red 50%</div> <div class="opBkg blue op80">Blue 80%</div> 

Matching CSS

 .opBkg { position: relative; } .opBkg:after { content: ''; position: absolute; z-index: -1; top: 0; right: 0; left: 0; bottom: 0; } .red:after { background-color: red; } .blue:after { background-color: blue; } .op10:after { opacity: .1; } .op50:after { opacity: .5; } .op80:after { opacity: .8; } 

You will have 10 opacity rules, any number of colors, and then a comprehensive opBkg class for customization.

+6
source

You will need to explicitly create 10 rules or have a preprocessor, for example SASS / Compass to do this for you.

The only other option would be to set the opacity dynamically using JavaScript based on some attribute indicating the degree of transparency. The following steps use jQuery to accomplish this:

 <div class="red" data-opacity=".75"></div> <div class="red" data-opacity=".50"></div> <div class="red" data-opacity=".25"></div> 
 $(".red").css("background-color", function (index, old) { var data = { color: old.match(/[0-9, ]+/), alpha: $(this).data("opacity") }; return "rgba(" + data.color + ", " + data.alpha + ")"; }); 

Fiddle: http://jsfiddle.net/jonathansampson/WYDJL/

+3
source

All Articles