Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53603

How do you add different opacities to nested items?

I have two nested items in HTML and I want to give the wrraping one opacity 0.8 and the one inside it opacity 1.
I think I understand why it does not work, but, how can I mimick that effect?
Here is a simplified HTML that shows the problem, I want the green square to be solid.

<div style='background-color:red;
            width: 500px;
            height: 500px;
            border: 1px solid black;
            position: absolute;
            top:0;
            left:0;
            opacity:0.8'>

    <div style='width:150px; height:150px; background-color:green; opacity:1'>
      Some content
    </div>
</div>

Upvotes: 5

Views: 4796

Answers (3)

Graham Conzett
Graham Conzett

Reputation: 8454

If you use the rgba CSS property instead of the opacity property you can achieve this:

<div style='background-color:rgba(0, 255, 0, 0.8) ;width: 500px; height: 500px; border: 1px solid black; position: absolute; top: 0; left: 0'>
<div style='position: relative; width: 150px; height: 150px; background-color: rgba(0, 0, 255, 1);'>aaaaaaaaa<br>aaaaaaaaa<br></div>
</div>

Demo: http://jsfiddle.net/ScHgC/

Upvotes: 9

Marc Audet
Marc Audet

Reputation: 46785

Using CSS2

I fiddled a demo for you that illustrates a key concept:

http://jsfiddle.net/audetwebdesign/pN69F/

You can start by adding a wrapper div to position your two enclosed div's, outer and inner. The outer comes before the inner, which means that the inner will sit over the outer (unless you adjust the z-index values).

You can set the opacity to the outer div and that will allow any background text or image to be partly visible. Set the opacity of the inner div to 1.0 to get fully saturated coloring.

I think most browsers support opacity, but check out http://www.quirksmode.org/css/opacity.html for vendor-specific CSS properties to handle IE quirks.

Upvotes: 0

stephenmurdoch
stephenmurdoch

Reputation: 34613

you could always embrace progressive enhancement and use rgba on your background-colors

// this will only affect the div it's applied to and not it's contents
background-color: rgba(0,0,0,0.8)

Upvotes: 1

Related Questions