Peter
Peter

Reputation: 1160

My child div's opacity keeps inheriting from its parent. How can I stop that behavior?

I simply can't figure out why the <div id="icon-menu"> still has the same opacity as the ancestor <div class="box">. As far as I know, according to CSS specificity, that shouldn't happen.

<div class="jumbotron">    
    <div class="box">
        <div id="icon-menu" style="opacity: 1">
            <i class="fa fa-bars"></i>
            Menu
        </div>
    </div>
</div>

This is my CSS:

.box {
    background-color: #000000;
    height: 60px;
    min-width: 100%;
    opacity: 0.5;
}

#icon-menu {
    opacity: 1;
    padding-left: 75px;
    position: fixed;
    color: #ffffff;
    font-size: 40px;
}

As you can see, I tried some ways to change the opacity of the <div id="icon-menu:> back to 1, but nothing has an effect. Do you have a clue what's wrong?

Upvotes: 0

Views: 573

Answers (3)

j08691
j08691

Reputation: 207861

While you can't use opacity to make a descendant element more opaque than the parent, you can use rgba coloring to do what you want:

.box {
    background-color: rgba(0, 0, 0, .5);
    height: 60px;
    min-width: 100%;
}
#icon-menu {
    background-color: rgba(0, 0, 0, 1);
    padding-left: 75px;
    position: fixed;
    color: #ffffff;
    font-size: 40px;
}

jsFiddle example

Upvotes: 3

David Oliver
David Oliver

Reputation: 2502

It's because #icon-menu is inside .box, and the opacity applies to all children. This isn't a CSS specificity issue, but rather the way that opacity is applied.

Upvotes: 0

Steve Sanders
Steve Sanders

Reputation: 8651

You cannot override opacity in child elements. From MDN:

The value applies to the element as a whole, including its contents, even though the value is not inherited by child elements. Thus, an element and its contained children all have the same opacity relative to the element's background, even if the element and its children have different opacities relative to one another.

https://developer.mozilla.org/en-US/docs/Web/CSS/opacity

Upvotes: 4

Related Questions