使容器具有透明度

xiechengyu ... 2018-11-20 14:56:01 笔记
  • Html
  • Css
大约 2 分钟

# 前言

需要在点击某个按钮之后出现弹层,但是我在一开始写弹层的时候是直接使包裹外部的弹层具有opcity属性,但是结果发现里面本该显示的弹层的内容也继承了其opcity属性,由此我就自己找出了几个解决方法。

# 遇到的问题

<!-- html部分 -->
<div class="div1">
    <div class="div2">haha</div>
</div>
1
2
3
4
// css部分
 body{
     background: #00f;
 }
.div1 {
     width: 500px;
     height: 500px;
     background: #000;
     opacity: 0.4;
     position: relative;
 }
 .div1 .div2 {
            background: #f00;
            width: 200px;
            height: 200px;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -100px;
            margin-top: -100px;
            opacity: 1;
 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

最后显示的样式是这样的,里面的颜色明显受到其父容器opcity元素的影响。

t1

那我们应该怎么解决呢。

# 解决方法

# 使用一张透明的图片做背景可以达成效果

就是说把div1直接用一张透明的图片作为背景。

改过后的css代码如下:

body{
   background: #00f;
}
.div1 {
     width: 500px;
     height: 500px;
     background: url("/assets/img/tou/t2.png");
     position: relative;
}
.div1 .div2 {
          background: #f00;
          width: 200px;
          height: 200px;
          position: absolute;
          left: 50%;
          top: 50%;
          margin-left: -100px;
          margin-top: -100px;
          opacity: 1;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

最后的显示如下:

t3

# 使用rgba属性来完成

我们知道RGBA是代表Red(红色 (opens new window)Green(绿色 (opens new window)Blue(蓝色 (opens new window))和Alpha的色彩空间 (opens new window)。而其中的Alpha的用法和opcity的用法很相似,所以我们所期望的效果背景为黑,且透明度为0.4可以这样来实现。

其改后的css代码如下:

body{
   background: #00f;
}
.div1 {
     width: 500px;
     height: 500px;
     background: url("/assets/img/tou/t2.png");
     position: relative;
}
.div1 .div2 {
          background: #f00;
          width: 200px;
          height: 200px;
          position: absolute;
          left: 50%;
          top: 50%;
          margin-left: -100px;
          margin-top: -100px;
          opacity: 1;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

t4

我们看到也能实现其效果。

大概就是这样了,希望日后再遇到能够有更多方法解决!!!

上次编辑于: 2022年2月8日 15:39
贡献者: xiechengyu