How to apply an opacity without affecting a child element with html/css?

前端 未结 12 2277
臣服心动
臣服心动 2020-11-29 04:12

I want to achieve this using html and css:

\"schema\"

I have tried to set the opacity of the container

12条回答
  •  醉梦人生
    2020-11-29 04:36

    You can't apply an opacity property without affecting a child element!

    "Opacity applies to the element as a whole, including its contents, even though the value is not inherited by child elements. Thus, the element and its children all have the same opacity relative to the element's background, even if they have different opacities relative to one another... If you do not want to apply opacity to child elements, use the background property instead." https://developer.mozilla.org/en-US/docs/Web/CSS/opacity

    If you want the opacity to be applied only to the background, without affecting the child elements, use:

    background-color: rgba(255, 255, 255, .3)

    However, you can achieve the desired effect if you place them inside a div parent element and use CSS position property:

    .parent {
      border: solid green 3px;
      position: relative;
      width: 400px;
      height: 200px;
    }
    
    .sibling-one {
      border: solid red 3px;
      position: absolute;
      box-sizing: border-box;
      width: 400px;
      height: 200px;
      opacity: .3;
     }
    
    .sibling-two {
        border: solid blue 1px;
        margin: 10px;
        width: 200px;
        height: 100px;
        position: absolute;
        transform: translateY(50%);
    }  

    A sibling's one element

    A sibling's two element

提交回复
热议问题