WEEK: 7
Active: Not Currently Active
Work Due:

Opacity

In addition to setting the color of background elements and text, we developers may dictate the opacity of elements themselves of just the background-color of an element.

Opacity is set as a ration between 0.0 - 1.0. This controls how much, if at all, elements behind the element in question may be seen. A value of 0.0 would make the element in question invisible, and 1.0, make it totally opaque.

There are two ways to dictate opacity.

Background Opacity

In order to change the opacity of the background-color only, you can pass rgba() (as opposed to rgb()).

Like, rgb(), rgba(), takes three numbers to define the ratios of red, green, & blue. However, rgba() also take a fourth number, in the range of 0.0-1.0, to define the opacity level.

CSS
* {
    rgba(0, 0, 0, 0.5);
}

Element Opacity

If the goal is to change the opacity of an entire element, as well as its contents, then you can call the separate opacity: property. Like the fourth argument for rgba(), this property takes a single number, between 0.0-1.0, to represent the opacity of an element.

CSS
div.inner-container {
    opacity: 0.5;
}

Example

The following Example creates 4 elements.

  1. .body-1 is the furthest back, and has no opacity values set.
  2. .box-1-inner is nested within box one. The color is set to green, and CSS specifies the opacity: property be set to 0.5. Notice how both the color of the box, as well as the white text, are effected by the red of box-1.
  3. box-2 is a separate element, which has been positioned to overlap the other two boxes. Notice that it uses the rgba() property, which allows the background color to allow bleed through, but NOT the text.
  4. image-box is just a flat, black, logo of a buff. It uses the opacity: property, and as such, allows the other three boxes to bleed through it.
CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
body {
font-size: 24pt;
color: white;
}
.box-1 {
background-color: rgb(255, 0, 0);
height: 250px;
}

.box-1-inner {
background-color: rgb(0, 255, 0);
opacity: 0.5;
width: 60%;
height: 300px;
margin-left: 10%;
}

.box-2 {
background-color: rgba(0, 0, 255, 0.5);
position: absolute;
left: 50px;
top: 130px;
width: 40%;
height: 300px;
}

.image-box {
position: absolute;
top: 150px;
left: 0px;
opacity: 0.5;

}

img {
width: 150%;
}
HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<body>
<div class="box-1">
box 1 - red
<div class="box-1-inner">
inner box - green
</div>
</div>

<div class="box-2">
box 2 - blue
</div>

<div class="image-box">
<img src="./imgs/buff_icon_right.png" alt="Buffalo Icon">
</div>
</body>
[Code Download] [View on GitHub] [Live Example]

Previous section:
Next section: