彻底弄懂css中的透明度

有时候,我们在css设置透明度来实现特殊的效果。css中共有两种透明度方式:opacity和rgba,那么两者又有什么区别呢?

opacity

    <style>
        /* opacity设置透明度,会给父元素里的所有子元素也设置 */
        #box {
            width: 200px;
            height: 200px;
            position: relative;
            margin: auto;
            background-color: red;
            opacity: 0.5;
        }

        #content {
            width: 100px;
            height: 100px;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            line-height: 100px;
            text-align: center;
        }
    </style>
    
    
    <div id="box">
        <div id="content">这是内容</div>
    </div>
复制代码

image.png
opacity设置的透明度会被子元素继承。

rgba

    <style>
        /* rgba只能给颜色设置透明度,并且不会影响到子元素 */
        #box {
            width: 200px;
            height: 200px;
            position: relative;
            margin: auto;
            background-color: rgba(0, 0, 0, 0.3)
        }

        #content {
            width: 100px;
            height: 100px;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            line-height: 100px;
            text-align: center;
        }
    </style>
    
    <div id="box">
        <div id="content">这是内容</div>
    </div>
复制代码

image.png
rgba设置的透明度则不能被子元素给继承。


记录记录!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享