0

I am trying to prevent the opacity property from applying to the child elements.

I was under the assumption that the below piece of code would do that, but it isn't working.

.22:hover:after {
background-color: black;
opacity: 0.1;
}
sephiith
  • 1,187
  • 3
  • 23
  • 47
  • possible duplicate of [CSS to prevent child element from inheriting parent styles](http://stackoverflow.com/questions/5080365/css-to-prevent-child-element-from-inheriting-parent-styles) – Matt Ball May 24 '13 at 05:13
  • Possible duplicate of [CSS: semi-transparent background, but not text](http://stackoverflow.com/q/806000/2109908) –  May 24 '13 at 05:19
  • possible duplicate of [How do I prevent CSS inheritance?](http://stackoverflow.com/questions/958170/how-do-i-prevent-css-inheritance) – hjpotter92 May 26 '13 at 11:38

2 Answers2

3

One solution is using rgba:

.22:hover:after {
    background-color: rgba(0, 0, 0, 0.1); // black with opacity 0.1
}
0

The reason your current solution doesn't work is because your :after pseudo element does not have any content set (therefore it is not rendered), and it is not positioned properly. Try this instead.

.22:hover:after
{
    background-color: #000;
    opacity: 0.1;        
    content: ' ';
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 0px;  
    left: 0px;    
}

It works because the :after pseudo element renders inside the element which it is meant to come after, by then positioning and setting this pseudo element to always be the same size as its parent element, you get a parent element with a transparent background.

You should also make sure that you child element has its position property set (because setting the z-index doesn't work without a position property set) and az-index higher than the z-index of the :after pseudo element (1 is fine in this case):

.22 > yourchildelement
{
    position: relative;
    z-index: 1;
}

That should do the trick for you. Here's a jsFiddle, the background is set to be black.

Mathijs Flietstra
  • 12,900
  • 3
  • 38
  • 67