简体   繁体   English

防止不透明度CSS应用于子元素

[英]Prevent opacity css from applying to child elements

I am trying to prevent the opacity property from applying to the child elements. 我试图防止将opacity属性应用于子元素。

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

One solution is using rgba : 一种解决方案是使用rgba

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

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. 当前解决方案不起作用的原因是:after伪元素没有任何内容集(因此未呈现),并且没有正确放置。 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. 之所以起作用,是因为:after伪元素将在它要使用的元素内部进行渲染,然后通过将该伪元素定位并设置为始终与其父元素相同的大小,可以得到具有透明背景的父元素。

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 a z-index higher than the z-index of the :after pseudo element ( 1 is fine in this case): 你还应该确保你的孩子元素都有position属性集(因为设置z-index没有一个不工作position属性集)和z-index比更高z-index的的:after伪元素( 1在这种情况下很好):

.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. 这是一个jsFiddle ,背景设置为黑色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM