Random Transparency Tip

March 9, 2012

My personal web design aesthetic (for the time being) involves transparent backgrounds. I like the layering effect it creates and the subtle depth it gives a website.

The standard way of creating transparent elements with CSS is as follows:

div.transparent {
filter: alpha(opacity=50);
opacity: 0.5;
}

As you may have deduced, the example above applies a class that makes the div 50% transparent. Which can be modified to reflect whichever percentage you prefer. I typically use 80% or 85% in my designs. The problem with this method is that it makes everything in that div transparent as well, including text that you would probably prefer to be legible to your user.

In considering this problem, I conceived of two possible solutions. The first would be to place text in a separate div and move that text div with positioning and z-index so that it was directly above the transparent background div. The problem with this would be that if either of the two divs are fluid, the divs won’t remain lined up. That is, any change in the size, shape or number of words in the text div would cause the words to not “fit inside” the transparent div. Plus, positioning can be tricky and should probably be avoided if possible.

The other solution, the one that I prefer, is to create a transparent png in Photoshop and use it as a background image.


div.transparent {
background-image:url('images/transbg.png');
}

The advantage of this option is that the shape and size of the div are entirely flexible and can be fluid to whatever content you put in it. I’m liking rounded corners these days and haven’t noticed any weirdness caused by combining them with transparent png backgrounds. The disadvantage of this method would be that if you want to adjust the level of transparency, you would need to create a completely different png file. The use of a graphic file also adds some extra weight to your page, but if you use a 10 pixel by 10 pixel png, that difference won’t make much of a difference. The image I’m using on my current project (here) is 2.7 KB, and I don’t think that’s going to kill anybody’s bandwith.

A final note: I seem to remember reading somewhere that transparent png patterns can cause weird striations if they are smaller than 10×10. I don’t know if that’s accurate, or if it’s something that’s been fixed in current browsers, but it’s probably better to not to go smaller without testing it thoroughly.