Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

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.

like image 328
Googlebot Avatar asked Jan 10 '13 15:01

Googlebot


People also ask

How do you combine colors in CSS?

The color-mix() functional notation takes two color values and returns the result of mixing them in a given colorspace by a given amount.

Can a background color be transparent CSS?

The CSS color name transparent creates a completely transparent color. Using rgba or hsla color functions, that allow you to add the alpha channel (opacity) to the rgb and hsl functions. Their alpha values range from 0 - 1.

Is transparent a valid CSS color?

A <color> can be defined in any of the following ways: Using a keyword (such as blue or transparent ). All existing keywords specify a color in the sRGB color space.

Is there a color code for transparent?

You can actually apply a hex code color that is transparent. The hex code for transparent white (not that the color matters when it is fully transparent) is two zeros followed by white's hex code of FFFFFF or 00FFFFFF.


1 Answers

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.

like image 66
ScottS Avatar answered Sep 20 '22 12:09

ScottS