Is it possible, using CSS only, to make the background
of an element semi-transparent but have the content (text & images) of the element opaque?
I'd like to accomplish this without having the text and the background as two separate elements.
When trying:
p {
position: absolute;
background-color: green;
filter: alpha(opacity=60);
opacity: 0.6;
}
span {
color: white;
filter: alpha(opacity=100);
opacity: 1;
}
<p>
<span>Hello world</span>
</p>
It looks like child elements are subjected to the opacity of their parents, so opacity:1
is relative to the opacity:0.6
of the parent.
If you're using Less, you can use
fade(color, 30%)
.You can use RGB color with opacity like this color code in RGB (63,245,0) and add opacity like (63,245,0,0.5) and also add RGBA replace RGB. A use for opacity
There is a trick to minimize the markup: Use a pseudo element as the background and you can set the opacity to it without affecting the main element and its children:
DEMO
Output:
Relevant code:
Browser support is Internet Explorer 8 and later.
The easiest method would be to use a semi-transparent background PNG image.
You can use JavaScript to make it work in
Internet Explorer 6
if you need to.I use the method outlined in Transparent PNGs in Internet Explorer 6.
Other than that,
you could fake it using
two side-by-side sibling elements
- make one semi-transparent, thenabsolutely position the other over the top
?This method allows you to have an image in the background and not only a solid color, and can be used to have transparency on other attributes such as borders. No transparent PNG images are required.
Use
:before
(or:after
) in CSS and give them the opacity value to leave the element at its original opacity. Thus you can use :before to make a faux element and give it the transparent background (or borders) you want and move it behind the content you want to keep opaque withz-index
.An example (fiddle) (note that the
DIV
with classdad
is just to provide some context and contrast to the colors, this extra element is actually not needed, and the red rectangle is moved a bit down and to the right to leave visible the background behind thefancyBg
element):with this CSS:
In this case
.fancyBg:before
has the CSS properties you want to have with transparency (red background in this example, but can be an image or borders). It's positioned as absolute to move it behind.fancyBg
(use values of zero or whatever is more appropriate for your needs).