The opacity
property defines the transparency level of an element.
The opacity
property accepts values ranging from 0.0 to 1.0 (0% to 100%). A lower value indicates higher transparency.
Transparent Image
Here we have a transparent image example:
.image-one {
opacity: 0.2;
}
.image-two {
opacity: 0.5;
}
.image-three {
opacity: 1;
}
In the example:
- The first image has
opacity: 0.2;
, making it highly transparent. - The second image has
opacity: 0.5;
, giving it 50% transparency. - The third image has
opacity: 1;
, making it fully opaque with no transparency.
Transparent Hover Effect
The opacity
property is often used with the :hover
selector to change the transparency when the mouse hovers over an element.
img {
opacity: 0.5;
}
img:hover {
opacity: 1.0;
}
In the above example, the image has 50% transparency by default, but it will become fully opaque when the user hovers over it, as you can see in the below preview.
Transparent Box
When you use the opacity
property to make the background of an element transparent, it also affects the transparency of all its child elements. This can result in the text within the element becoming difficult to read if the background is too transparent.
.box1 {
background:skyblue;
opacity: 1;
}
.box2 {
background:skyblue;
opacity: 0.6;
}
.box3 {
background:skyblue;
opacity: 0.3;
}
.box4 {
background:skyblue;
opacity: 0.1;
}
Transparency using RGBA
If you want to ensure that only the background color is affected by opacity, not the child elements, use RGBA color values. The following example applies opacity to the background color while keeping the text fully opaque:
.box1 {
background: rgba(135, 206, 235, 1);
}
.box2 {
background: rgba(135, 206, 235,0.6);
}
.box3 {
background: rgba(135, 206, 235, 0.3);
}
.box4 {
background: rgba(135, 206, 235, 0.1);
}
An RGBA color value is defined as: rgba(red, green, blue, alpha). The alpha parameter ranges from 0.0 (completely transparent) to 1.0 (completely opaque).
Note: You can learn more about RGBA Colors in our HTML RGB and RGBA Colors tutorial.
Text in a Transparent Box
RGBA values are particularly useful in creating text overlays with transparent background above images and other elements in web pages.
<div class="background">
<div class="box">
<p>Text in a transparent box</p>
</div>
</div>
.background {
background: url(image.png) no-repeat;
border: 1px solid red;
}
.box {
margin: 30px;
border: 1px solid black;
background: rgba(0,0,0,0.5);
}
.box p {
margin: 5%;
font-weight: bold;
color: #FFFFFF;
}
The preview of above example is shown below.