CSS opacity only to background color, not the text on it?

The easiest way to do this is with 2 divs, 1 with the background and 1 with the text:

#container {
  position: relative;
  width: 300px;
  height: 200px;
}
#block {
  background: #CCC;
  filter: alpha(opacity=60);
  /* IE */
  -moz-opacity: 0.6;
  /* Mozilla */
  opacity: 0.6;
  /* CSS3 */
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}
#text {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<div id="container">
  <div id="block"></div>
  <div id="text">Test</div>
</div>

I had the same problem. I want a 100% transparent background color. Just use this code; it's worked great for me:

rgba(54, 25, 25, .00004);

You can see examples on the left side on this web page (the contact form area).


It sounds like you want to use a transparent background, in which case you could try using the rgba() function:

rgba(R, G, B, A)

R (red), G (green), and B (blue) can be either <integer>s or <percentage>s, where the number 255 corresponds to 100%. A (alpha) can be a <number> between 0 and 1, or a <percentage>, where the number 1 corresponds to 100% (full opacity).

RGBa example

background: rgba(51, 170, 51, .1)    /*  10% opaque green */ 
background: rgba(51, 170, 51, .4)    /*  40% opaque green */ 
background: rgba(51, 170, 51, .7)    /*  70% opaque green */ 
background: rgba(51, 170, 51,  1)    /* full opaque green */ 

A small example showing how rgba can be used.

As of 2018, practically every browser supports the rgba syntax.


For Less users only:

If you don't like to set your colors using RGBA, but rather using HEX, there are solutions.

You could use a mixin like:

.transparentBackgroundColorMixin(@alpha,@color) {
  background-color: rgba(red(@color), green(@color), blue(@color), @alpha);
}

And use it like:

.myClass {
    .transparentBackgroundColorMixin(0.6,#FFFFFF);
}

Actually this is what a built-in Less function also provide:

.myClass {
    background-color: fade(#FFFFFF, 50%);
}

See How do I convert a hexadecimal color to rgba with the Less compiler?

Tags:

Css

Opacity