Googlebot
Googlebot

Reputation: 15683

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

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

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

with CSS

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

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

I have 10 solid colors, and want to create 10 level of transparency for each. If individually making the transparent color for each color, it needs 100 CSS classes; e.g.:

.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 the solid color and a transparent background.

Upvotes: 6

Views: 3627

Answers (2)

Sampson
Sampson

Reputation: 268344

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

The only other option would be to set the opacity dynamically with JavaScript based on some attribute indicating degree of transparency. The following uses 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/

Upvotes: 3

ScottS
ScottS

Reputation: 72261

Pure CSS

Yes, you can disassociate the color and transparency by creative use of pseudo-elements. For example, this fiddle demonstrates the following code (notice I have arranged everything based on the :after pseudo-element):

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>

Relevant 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 would have 10 opacity rules, however many colors you want, and then the overarching opBkg class to set things up.

Upvotes: 8

Related Questions