解决父元素opacity会影响子元素的问题

如何使父元素的opacity不影响子元素

前言

现有一个粉红色父元素,包裹着绿色子元素,效果如下

在这里插入图片描述

代码如下

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .border{
     
		border: 2px solid #333;
      }
      .father {
     
        width: 400px;
        height: 400px;
        background-color: #CD5C5C;
      }
      .son {
     
        width: 200px;
        height: 200px;
        background-color: #32CD32;
      }
    </style>
  </head>
  <body>
    <div class="border">
      <div class="father">
        father
        <div class="son">son</div>
      </div>
    </div>
  </body>
</html>

如果一个父元素设置opacity:0.5,那么他的子元素也会受到影响,即使将子元素的opacity设为1也不会正常显示。

在这里插入图片描述

在这里插入图片描述

解决方法

方法一(推荐

将十六进制的颜色转为rgba写法,将透明度给rgba的第四个参数

原先写法

.father{
   
	width: 400px;
    height: 400px;
    opacity: 0.5;
    background-color: #CD5C5C;
}

修改后写法

.father{
   
	width: 400px;
    height: 400px;
    background-color: rgba(205, 92, 92, 0.5);
}

最终效果

在这里插入图片描述

方法二(可以实现,但没必要

如果父元素只是一个背景,可以利用定位,使元素脱离文档流

修改后代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .border {
   
        position: relative;
        border: 2px solid #333;
      }
      .father {
   
        position: absolute;
        width: 400px;
        height: 400px;
        background-color: #cd5c5c;
        opacity: 0.5;
      }
      .son {
   
        position: absolute;
        width: 200px;
        height: 200px;
        background-color: #32cd32;
      }
    </style>
  </head>
  <body>
    <div class="border">
      <div class="father">father</div>
      <div class="son">son</div>
    </div>
  </body>
</html>

在这里插入图片描述

可以发现最外层的元素由于受到定位影响(子元素脱离文档流,其本身又未设置高度),导致高度为0,宽度默认100%,还需要手动设置宽高,所以不建议这种写法。

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-15 06:10:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-15 06:10:01       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-15 06:10:01       82 阅读
  4. Python语言-面向对象

    2023-12-15 06:10:01       91 阅读

热门阅读

  1. Angular 2 学习笔记

    2023-12-15 06:10:01       52 阅读
  2. Android笔记:SwipeRefreshLayout 自动刷新

    2023-12-15 06:10:01       51 阅读
  3. 数据仓库相关概念

    2023-12-15 06:10:01       67 阅读
  4. c语言多线程队列实现

    2023-12-15 06:10:01       54 阅读
  5. Redis—SpringDataRedis

    2023-12-15 06:10:01       40 阅读
  6. npm install -g node-gyp error -13

    2023-12-15 06:10:01       48 阅读
  7. conda保姆级使用教程

    2023-12-15 06:10:01       66 阅读
  8. C#函数(方法)

    2023-12-15 06:10:01       54 阅读
  9. xcode-文件

    2023-12-15 06:10:01       61 阅读
  10. CollectionUtils 包

    2023-12-15 06:10:01       88 阅读