css实现背景颜色半透明的两种方法及区别

江河/ 2023年05月06日/ CSS教程/ 浏览 643

css 实现背景半透明有两种方法,rgba设置背景色 和 opacity 属性。两种方法在实现的效果上有所差异,通过实例可更好的说明。


一、使用 rgba 设置背景色。


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
    <title>CSS实现背景色半透明的两种方法</title>
    <style>
        .background {
            width: 160px;
            height: 160px;
            padding: 50px;
            
            background-color: rgba(0, 255, 0, 0.5);
        }

        .content {
            width: 160px;
            height: 160px;
            background-color: red;
        }
    </style>
</head>

<body>
    <div class="background">
        <div class="content">我是内容</div>
    </div>
</body>

</html>


效果如下:

二、使用 opacity 属性。


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
    <title>CSS实现背景色半透明的两种方法</title>
    <style>
        .background {
            width: 160px;
            height: 160px;
            padding: 50px;
            
            background-color: green;
            opacity: 0.5; 
        }

        .content {
            width: 160px;
            height: 160px;
            background-color: red;
        }
    </style>
</head>

<body>
    <div class="background">
        <div class="content">我是内容</div>
    </div>
</body>

</html>


效果如下:


通过对比两种方法的区别就很清楚了:rgba 是让元素本身背景色半透明,而 opacity 是让元素及其子元素全部半透明。


在实践中,有时会遇到必须使用 opacity 属性,而有不希望子元素半透明的需求。这时可以通过改变元素父子关系及定位方式的方法,让元素看上去还有父子关系。


比如,还使用上面的例子,修改如下:


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
    <title>CSS实现背景色半透明的两种方法</title>
    <style>
        .background {
            width: 160px;
            height: 160px;
            padding: 50px;

            background-color: green;
            opacity: 0.5;
        }

        .content {
            position: absolute;
            top: 55px;
            left: 55px;

            width: 160px;
            height: 160px;
            background-color: red;
        }
    </style>
</head>

<body>
    <div class="background"></div>
    <div class="content">我是内容</div>
</body>

</html>


效果如下:


发表评论

暂无评论,抢个沙发...

客服 工单