CSS/HTML Opacity and Transparency

CSS3 lets you specify opacity and transparency with an additional parameter that ranges from 0 to 1. A value of 0 means the object is totally transparent, while a value of 1 means totally opaque. Intermediate values can be used to create translucent elements, such as text, background colors, and images.

There are several ways to indicate the opacity/transparency of an object in CSS. The major techniques are explained below with examples.

Translucent Colors: RGBA and HSLA

The images below is overlaid with CSS text at different levels of opacity. The colors and their transparencies are specified using the 4-parameter RGBA and HSLA color systems, extensions of the RGB and HSL systems. The first three parameters are R, G, and B; and H, S, and L respectively. The fourth parameter, alpha, controls the opacity. The first image shows the RGBA code, the second shows the HSLA code.

color:rgba(200,0,60,1)
color:rgba(200,0,60,0.75)
color:rgba(200,0,60,0.5)
color:rgba(200,0,60,0.25)

color:hsla(226,100%,50%,1)
color:hsla(226,100%,50%,0.75)
color:hsla(226,100%,50%,0.5)
color:hsla(226,100%,50%,0.25)

The lines decrease in opacity from 1 to 0.25. In case you can't read the CSS codes, they are:
color:rgba(200,0,60,1)
color:rgba(200,0,60,0.75)
color:rgba(200,0,60,0.5)
color:rgba(200,0,60,0.25)

color:hsla(226,100%,50%,1)
color:hsla(226,100%,50%,0.75)
color:hsla(226,100%,50%,0.5)
color:hsla(226,100%,50%,0.25)

Opacity Attribute

You can also add the opacity attribute to elements to make them more transparent. Below, the image's opacity level has been set to 0.45



The CSS code is
img {
  opacity:0.45;
  filter:alpha(opacity=45); /* IE 8 and earlier */
}
All major browsers except Internet Explorer 8 and below can parse the "opacity" attribute. For older versions of IE, you must also include the second line. Including both lines ensures cross-browser compatibility.

The opacity attribute can be applied to text boxes as well. The same image, now with a translucent text box, border, and text:

Chickens



The code used to generate this is
div .outer {
  width:94%;
  height:350px;
  border:1px solid #000000;
  background-image:url(chicken.png);
}

div. inner {
  width:80%;
  height:260px;
  margin-top:30px;
  margin-left:15px;
  border:15px solid #0066cc;
  background-color:#66bb44;
  color:#005500;
  font-size:20px;
  opacity:0.5;
  filter:alpha(opacity=50);
}


© Had2Know 2010