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


Can I assign the opacity property to the background property of a div only and not to the text on it?

I've tried:

background: #CCC;
opacity: 0.6;

but this doesn't change the opacity.

3/30/2019 9:44:35 PM

Accepted Answer

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

rgba(51, 170, 51, .1)    /*  10% opaque green */ 
rgba(51, 170, 51, .4)    /*  40% opaque green */ 
rgba(51, 170, 51, .7)    /*  70% opaque green */ 
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.

6/20/2020 9:12:55 AM

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>


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 {

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?


This will work with every browser

div {
    -khtml-opacity: .50;
    -moz-opacity: .50;
    -ms-filter: ”alpha(opacity=50)”;
    filter: alpha(opacity=50);
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
    opacity: .50;

If you don't want transparency to affect the entire container and its children, check this workaround. You must have an absolutely positioned child with a relatively positioned parent to achieve this. CSS Opacity That Doesn’t Affect Child Elements

Check a working demo at CSS Opacity That Doesn't Affect "Children"


My trick is to create a transparent .png with the color and use background:url().


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).


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]