sephiith
sephiith

Reputation: 1197

Prevent opacity css from applying to child elements

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;
}

Upvotes: 0

Views: 740

Answers (2)

Mathijs Flietstra
Mathijs Flietstra

Reputation: 12974

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.

Upvotes: 0

user1823761
user1823761

Reputation:

One solution is using rgba:

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

Upvotes: 3

Related Questions