Opacity of background-color, but not the text
CssOpacityCss Problem Overview
How do I make the cross-browser (including Internet Explorer 6) transparency for the background of a div
while the text remains opaque?
I need to do it without using any library such as jQuery, etc. (But if you know of a library that does it I'd love to know so I can look at their code).
Css Solutions
Solution 1 - Css
Use rgba!
.alpha60 {
/* Fallback for web browsers that don't support RGBa */
background-color: rgb(0, 0, 0);
/* RGBa with 0.6 opacity */
background-color: rgba(0, 0, 0, 0.6);
/* For IE 5.5 - 7*/
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
/* For IE 8*/
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";
}
> In addition to this, you have to declare background: transparent
for IE web browsers, preferably served via conditional comments or similar!
Solution 2 - Css
I use an alpha-transparent PNG for that:
div.semi-transparent {
background: url('semi-transparent.png');
}
Solution 3 - Css
I've created that effect on my blog Landman Code.
What I did was
#Header {
position: relative;
}
#Header H1 {
font-size: 3em;
color: #00FF00;
margin:0;
padding:0;
}
#Header H2 {
font-size: 1.5em;
color: #FFFF00;
margin:0;
padding:0;
}
#Header .Background {
background: #557700;
filter: alpha(opacity=30);
filter: progid: DXImageTransform.Microsoft.Alpha(opacity=30);
-moz-opacity: 0.30;
opacity: 0.3;
zoom: 1;
}
#Header .Background * {
visibility: hidden; // hide the faded text
}
#Header .Foreground {
position: absolute; // position on top of the background div
left: 0;
top: 0;
}
<div id="Header">
<div class="Background">
<h1>Title</h1>
<h2>Subtitle</h2>
</div>
<div class="Foreground">
<h1>Title</h1>
<h2>Subtitle</h2>
</div>
</div>
The important thing that every padding/margin and content must be the same in both the .Background as .Foreground.
Solution 4 - Css
Relaxing your requirement to work on IE6 and legacy browsers you can use ::before and display: inline-block
div
{
display: inline-block;
position: relative;
}
div::before
{
content: "";
display: block;
position: absolute;
z-index: -1;
width: 100%;
height: 100%;
background:red;
opacity: .2;
}
Demo at http://jsfiddle.net/KVyFH/172/ ā
It will work on any modern browser
Solution 5 - Css
Thanks @davy-landmann for https://stackoverflow.com/a/638064/417153. That's what I was looking for! Same effect with LESS code:
@searchResultMinHeight = 200px;
.searchResult {
min-height: @searchResultMinHeight;
position: relative;
.innerTrans {
background: white;
.opacity(0.5);
min-height: @searchResultMinHeight;
}
.innerBody {
padding: 0.5em;
position: absolute;
top: 0;
}
}