John
John

Reputation: 105

how do i apply opacity to a div wihout affecting the other elements within it?

Wen i apply opacity to a div, all the other elements within that div acquire the same opacity as the parent div, of which i want the children not to have any opacity. I would appreciate the help.

Upvotes: 0

Views: 3541

Answers (2)

BoltClock
BoltClock

Reputation: 724542

You can only control the alpha of certain individual components of your parent div using the rgba() color notation. Even then, browser support for rgba() is slightly poorer than support for opacity and you can't use vendor extensions with it:

#parent {
    color: rgba(255, 255, 255, 0.5);
    background-color: rgba(153, 0, 0, 0.5);
}

If you need browser support, use a transparent PNG image of the color instead:

#parent {
    color: rgba(255, 255, 255, 0.5);
    background-image: url(bg.png);
}

Do not set the opacity property; otherwise the opacity of everything inside your parent div will be relative to this opacity, and specifying parent opacity: 0.5 and child opacity: 2.0 won't work either.

Upvotes: 2

user123444555621
user123444555621

Reputation: 153284

Simple answer: it's not possible. You need to restructure your markup.

EDIT - You want an explanation, you get it.

The CSS specs state

<alphavalue>

Syntactically a <number>. The uniform opacity setting to be applied across an entire object. Any values outside the range 0.0 (fully transparent) to 1.0 (fully opaque) will be clamped to this range. If the object is a container element, then the effect is as if the contents of the container element were blended against the current background using a mask where the value of each pixel of the mask is <alphavalue>. .

Which means that, well, the containers opacity applies to its contents.

Workarounds using rgba colors won't affect images, form elements, scroll bars etc.

I therefore suggest a restructuring of the markup like this:

<div style="position: relative">
    <div style="position: absolute; top: 0; left: 0; opacity: .5">
        <!-- semi-transparent content here -->
    </div>
    <div style="position: absolute; top: 0; left: 0;">
        <!-- fully opaque content here -->
    </div>
</div>

Upvotes: 0

Related Questions