Alex Rivera | Logout

How do I reduce the opacity of an element's background using CSS?

Asked 2009-04-30T09:00:02.460
2554

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.

Edit
Report

1 Answer

8

background-color: rgba(255, 0, 0, 0.5); as mentioned above is the best answer simply put. To say use CSSĀ 3, even in 2013, is not simple because the level of support from various browsers changes with every iteration.

While background-color is supported by all major browsers (not new to CSSĀ 3) [1] the alpha transparency can be tricky, especially with Internet Explorer prior to version 9 and with border color on Safari prior to version 5.1. [2]

Using something like Compass or SASS can really help production and cross platform compatibility.


[1] W3Schools: CSS background-color Property

[2] Norman's Blog: Browser Support Checklist CSS3 (October 2012)

answered 2013-01-08T20:00:39.570

Your Answer