Disable opacity on child element when parent element has opacity

As the other answers state, this is not possible using opacity, that is, with this method.

A workaround/hack would be to add position: relative; z-index:2; to the parent element contentContainer. Then to add another element which has the opacity and other stuff on it. This is particularly useful if you have an image as the background

So your markup should look a little like this:

HTML

<div id="contentContainer">
    Content ...
    <img src="..." alt="Photo" />
    <span id="contentBackground"></span>
</div>

CSS

#contentContainer { position: relative; z-index 2; }
#contentBackground {
    position: absolute;
    display: block;
    z-index: 1;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: /* stuff */;
}

Note the z-index property. These are important for making sure that the background element sits below the parent and doesn't overlap the content preventing click events.

This method could also be used with pseudo elements (:before or :after) for which you'd need to add content: '';.


This might help others who would want to use opacity, preventing a certain child element from getting opaque.

You can use :not() Selector. Take this sample.

<style type="text/css">
    .redbg{
        background-color:red;
    }
    .sample1 :not(.NonOpaque){
        opacity:0.5;
    }
    .sample2:not(.NonOpaque){
        opacity:0.5;
    }
</style>

<div style="background-color:rgb(63,72,204); padding:15px; margin:15px;">
    <div class="redbg sample1">
        <div>
            SAMPLE 1.
        </div>
        <div class="NonOpaque">
            I am not Opaque.
            Blah! Blah! Blah!
        </div>
        <div>
            I am Opaque.
            Blah! Blah! Blah!
        </div>
        <div>
            I am Opaque.
            Blah! Blah! Blah!
        </div>
    </div>
</div>

<div style="background-color:rgb(63,72,204); padding:15px; margin:15px;">
    <div>SAMPLE 2.</div>
    <div class="redbg sample2 NonOpaque">
        <div style="padding:5px; margin:3px;">
            I am not Opaque.
            Blah! Blah! Blah!
        </div>
    </div>
    <div class="redbg sample2">
        <div style="padding:5px; margin:3px;">
            We are all Opaque.
        </div>
    </div>
</div>

Output:

enter image description here


Solved this problem by changing it to the following:

<div id="contentContainer" style="background: rgba(255,255,255,0.8);">
    Content ...
    <img src="..." alt="Photo" />
</div>

Used just rgba alpha instead of opacity. Now it works.

Tags:

Html

Css