0

I have following CSS

.dropdown-menu {
  background-color: black;
  opacity: 0.6;
  color: white;
}
.dropdown-menu > li {
  background-color: black;
  opacity: 1;
  color: white;
}

When HTML element (which uses this above CSS) is loaded I'm getting opacity sets as expected from .dropdown-menu, the problem is that this opacity is inherited inside dropdown-menu > li element event when I'm using an !important declaration on opacity.

So how to overcome this (Opacity should remain 0.6 on parent element) and on this child I want opacity 1?

m4n0
  • 29,823
  • 27
  • 76
  • 89
user1765862
  • 13,635
  • 28
  • 115
  • 220
  • Afaik this is not possible. If a parent element has opacity, all child elements have at most that opacity. If both the parent and child have .5 opacity, the child has effectively .25 opacity. – Sumurai8 Nov 15 '15 at 11:38
  • @Paulie_D Wrong question tagged as a duplicate and should be reopened or re voted to another question as a duplicate. – Mr. Alien Nov 15 '15 at 12:49

2 Answers2

5

Instead of using opacity for the parent element, declare your colors in rgba format.

.dropdown-menu {
  background-color: rgba(0,0,0,.6);
  color: rgba(255,255,255,.6);   
}

This way, you will retain the opacity of the parent element, as well as your child elements will have an opacity of 1.

Browser support for the same is pretty decent as well.


Also, I read this in your question, "The problem is that this opacity is inherited"

No, it isn't inherited.

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
2

It's important to know that opacity sets the opacity value for an element and all of its children; where RGBA sets the opacity value only for a single declaration.

So you should use something like:

.dropdown-menu {
    background-color: rgba(0,0,0,.6);
    color: rgba(255,255,255,.6);   
}

(Of course, you can also use the HSLA-property for this.)

Remember that the opacity-property isn't fully supported by all browsers, please check this SA-topic for more info on this: CSS background opacity with rgba not working in IE 8

Community
  • 1
  • 1
Sebass van Boxel
  • 2,514
  • 1
  • 22
  • 37