I see this being used in websites across the net and used in plugins for various common free CMS’ however I have never needed to set the set the background opacity without effecting child elements. It is surprising quite how much incorrect information is floating around on the internet which would results in everything being opaque.
Finally found an example which told me what I needed to know. Tested in the latest versions of FireFox, Chrome and Internet Explorer on the PC; also in Firefox, Safari and Chrome on the Mac.
Example:
Red background set to 50% opacity and white text
Here is the content.
Background should grow to fit.
Background should grow to fit.
Manage background opacity without effecting text
<style type="text/css">
.container
{
position:relative;
}
.content
{
position:relative;
color:White;
z-index:5;
padding:10px
}
.background
{
position:absolute;
top:0px;
left:0px;
width:100%;
height:100%;
background-color:Black;
z-index:1;
/* These three lines are for transparency in all browsers. */
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
filter: alpha(opacity=50);
opacity:.5;
}
</style>
<div class="container">
<div class="content">
Here is the content. <br />
Background should grow to fit.
</div>
<div class="background"></div>
</div>
How does it work?
- Main container is set to relative position. It contains the div with the opacity set and a div with the content you wish not to be affected;
- The div with the opaque background is absolutely positioned to top left. Because the containing div has a relative position the div will align itself to the top left of the containing div and not the top left of the page;
- The div with the copy and text is set to effectively float above the translucent background.
Credits
This solution comes thanks to Gorkem Pacaci from a StackOverflow answer