I do not want to inherit the child opacity from the parent in CSS

前端 未结 14 907
猫巷女王i
猫巷女王i 2020-11-21 06:31

I do not want to inherit the child opacity from the parent in CSS.

I have one div which is the parent, and I have another div inside the first div which is the child

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 06:40

    Opacity of child element is inherited from the parent element.

    But we can use the css position property to accomplish our achievement.

    The text container div can be put outside of the parent div but with absolute positioning projecting the desired effect.

    Ideal Requirement------------------>>>>>>>>>>>>

    HTML

                
    The text opacity is inherited from the parent div

    CSS

                   .container{
                    position:relative;
                                       }
               .bar{
                   opacity:0.2;
                   background-color:#000;
                   z-index:3;
                   position:absolute;
                   top:0;
                   left:0;
                  }
    
                  .text{
                    color:#fff;
    
                   }
    

    Output:--

    Inherited Opacity of Text(the text color is #000; but not visisble.)

    the Text is not visible because inheriting opacity from parent div.

    Solution ------------------->>>>>>

    HTML

           
    Opacity is not inherited from parent div "bar"

    CSS

                   .container{
                    position:relative;
                                       }
               .bar{
                   opacity:0.2;
                   background-color:#000;
                   z-index:3;
                   position:absolute;
                   top:0;
                   left:0;
                  }
    
                  .text{
                    color:#fff;
                    z-index:3;
                    position:absolute;
                   top:0;
                   left:0;  
                   }
    

    Output :

    Not Inherited

    the Text is visible with same color as of background because the div is not in the transparent div

提交回复
热议问题