views:

329

answers:

4

How to show the div content with semi background color but not the text value

Example:

<div style="height:25px; background-color: red;">
 Content 
</div>

I want to display the div background as semi transparent and text as normally while the onmouseover event.

How can I do that.

+1  A: 

Would something like this work?

<div class="wrapper" style="position:relative;">
    <div class="transparentBG" style="position:absolute;top:0;left:0;">Text</div>
    <div class="overlay" style="position:absolute;top:0;left:0;">Text</div>
</div>

You can set how the styles change by having ":hover" versions of each class.

You'll have fun with multi browser support though.

Alternatively you can use two images:

<style>
.transparentBGOnHover { background-image: url(../images/red.png); }
.transparentBGOnHover:hover { background-image: url(../images/transparentRed.png); }
</style>

<div class="transparentBGOnHover">
    Text
</div>

IE6 can't handle the transparent PNG correctly without a DX filter.

You may also need to handle the hover via javascript for IE6 and IE7 as they don't support :hover correctly (despite the fact that IE5.5 invented it)

Keith
A: 

Shouldn't this work just fine:

<div style="height:25px; background-color: #99FF0000;">
 Content 
</div>

Bobby

Bobby
or background-color:rgba(255,0,0, 0.5);more: http://css-tricks.com/rgba-browser-support/
pawel
@pawel: Nice, I always forget that CSS also has such functions.
Bobby
doesn't work in IE6-8
philfreo
A: 

You can't have non-transparent content in a semi-transparent container. The content inherits the transparency from the parent. Here's a solution which separates the content layer and the transparent layer. All is wrapped in a div which i target with the :hover rules.

This solution is only tested in FF3.5.4, note that IE 6 has problems with :hover on any other element then <A>.

<style type="text/css">
.wrapper { position: relative; }
.background { background-color: red; width: 100px; height:25px; position: absolute; }
.content { width: 100px; height: 25px; position: absolute; z-index: 2; color: #fff; }
.wrapper:hover .background { opacity: 0.25; }
.wrapper:hover .content { color: #000; }
</style>

<div class="wrapper">
    <div class="content">Text</div>
    <div class="background"></div>
</div>
Stoffe
A: 

This is basically the same question but has some better answers: http://stackoverflow.com/questions/806000/css-semi-transparent-background-but-not-text

philfreo