Transparent Backgrounds with CSS

Problem:

You’d like to have a transparent background upon an element, but you’re not quite sure how to do so.

Solution:

There are two methods you can use to create a transparent background for an element. To give a few examples on how we go about doing such, I’ll use a picture of Churuya-san.

1
<div class="box"></div>

Now onto our CSS for .box

1
2
3
4
5
6
7
.box {
 width: 225px;
 height: 188px;
 background: url('http://www.alemmer.com/wp-content/uploads/2009/04/tsuruya-nyoron_2.gif') center no-repeat #fff;
 margin: 10px auto 10px auto;
 border: 1px solid #343434;
}

Using a PNG

A simple way to create a transparent background is to use a transparent PNG as the background. We’ll place a div with the class “haiku” over Churuya-san (the div with the class “box”).

Kyon-kun, hey, Kyon-kun!
Is there any smoked cheese left?
No, you ate it all.
1
2
3
4
5
6
7
<div class="box">
 <div class="haiku">
  Kyon-kun, hey, Kyon-kun!<br />
  Is there any smoked cheese left?<br />
  <em>No, you ate it all.</em>
 </div>
</div>

Now onto our CSS for .haiku

1
2
3
4
5
6
.haiku {
 background: url('http://www.alemmer.com/wp-content/uploads/2009/04/haiku.png');
 padding: 2px;
 color: #fff;
 font-size: 0.8em;
}

Note that the transparent PNG (named “haiku”) is being set as the background on line number two.

Solely Using CSS

This method is a bit more complicated and requires a lot more code for a simple transparent background. I wouldn’t recommend this method for creating transparent backgrounds.

We’ll call our transparent div “cheese” and assign “cheese” as the class.

Smoked Cheese
1
2
3
4
5
<div class="box">
 <div class="cheese">
  <strong>Smoked Cheese</strong>
 </div>
</div>

Now onto our CSS for .cheese

1
2
3
4
.cheese {
 background: #000;
 padding: 2px;
 color: #fff;

Now we’ll start defining the transparency.

5
 filter:alpha(opacity=50);
For the statement above: 0 equals completely transparent, whereas 100 equals completely opaque.
6
7
8
9
 -moz-opacity:0.5;
 -khtml-opacity: 0.5;
 opacity: 0.5;
}

For the statements above: 0 equals completely transparent, whereas 1.0 equals completely opaque.

Note that the text “Smoked Cheese” is also transparent. This is because the child element inherits the parent element’s transparency settings.

There are ways to make the contents of the child element (in this case .cheese, as it is coded within .box) opaque, but they’re pretty ‘hackish’. If you’re really interested in using this method, Bits & Pixels explains how it can be done.

  • Facebook
  • Twitter
  • Reddit
  • email
  • del.icio.us
  • Digg
  • MySpace
  • Slashdot
  • Google Bookmarks
  • Live
  • StumbleUpon
  • Technorati

One Response to “Transparent Backgrounds with CSS”

  1. Mark says:

    Wow thats what i was looking for

Leave a reply