HTML/CSS - 如何实现父元素半透明,子元素不透明

1,537 阅读1分钟

问题描述

如果想要设置元素透明,简单的方式可以通过CSS属性opacity实现,但该属性会被子元素所继承,透明效果便会影响到子元素,并且子元素也不能通过充值opacity属性值的方式将透明效果消除

<style>
    .parent,.child,.gchild,.other {
        width: 300px;
        height: 250px;
        margin: 10px;
        display: inline-block;
        border-radius: 10px;
        text-align: center;
        color: white;
        background-color: red;
        vertical-align: middle; /* 三者都是设置为垂直居中,能让其并排显示 */
    }
    .parent{
        opacity: 0.5;   /* 设置透明度 */
    }
    .child{
        width: 200px;
        height: 150px;
        background-color: blue;
        opacity:1;      /* 重置透明度,也没有办法消除透明效果的影响 */
    }
    .gchild{
        width: 100px;
        height: 50px;
        background-color: green;
        opacity:1;      /* 重置透明度,也没有办法消除透明效果的影响 */
    }
</style>

<body>
    <div class="parent">
        <div class="child">
            <div class="gchild"></div>
        </div>
    </div>
    <div class="other">
        <div style="overflow: auto; width: 200px;height: 150px;background-color: blue;margin: 10px;border-radius: 10px;">
            <div style="width: 100px;height: 50px;background-color: green;margin: 10px;border-radius: 10px;">normal</div>
        </div>
    </div>
</body>

image.png

解决办法

使用CSS3规则里面的背景属性 rgba 取值,其中A可以设置透明度,该效果可以实现只影响一层元素,而不会让子元素继承,也就不会影响到子元素的透明度

<style>
    .parent,.child,.gchild,.other {
        width: 300px;
        height: 250px;
        margin: 10px;
        display: inline-block;
        border-radius: 10px;
        text-align: center;
        color: white;
        background-color: rgb(255, 0, 0);
        vertical-align: middle; /* 三者都是设置为垂直居中,能让其并排显示 */
    }
    .parent{
        background-color: rgba(255, 0, 0,0.5);   /* rgba设置透明度,子元素均不用再重置 */
    }
    .child{
        width: 200px;
        height: 150px;
        background-color: blue;
    }
    .gchild{
        width: 100px;
        height: 50px;
        background-color: green;
    }
</style>

<body>
    <div class="parent">
        <div class="child">
            <div class="gchild">transparent</div>
        </div>
    </div>
    <div class="other">
        <div style="overflow: auto; width: 200px;height: 150px;background-color: blue;margin: 10px;border-radius: 10px;">
            <div style="width: 100px;height: 50px;background-color: green;margin: 10px;border-radius: 10px;">normal</div>
        </div>
    </div>
</body>

image.png