How do I give text or an image a transparent background using CSS?

Stijn Sanders picture Stijn Sanders · Apr 30, 2009 · Viewed 1.5M times · Source

Is it possible, using CSS only, to make the background of an element semi-transparent but have the content (text & images) of the element opaque?

I'd like to accomplish this without having the text and the background as two separate elements.

When trying:

It looks like child elements are subjected to the opacity of their parents, so opacity:1 is relative to the opacity:0.6 of the parent.

Answer

Georg Schölly picture Georg Schölly · Apr 30, 2009

Either use a semi-transparent PNG image or use CSS 3:

background-color: rgba(255, 0, 0, 0.5);

Here's an article from css3.info, Opacity, RGBA and compromise (2007-06-03).


<p style="background-color: rgba(255, 0, 0, 0.5);">
  <span>Hello, World!</span>
</p>