CSS opacity
Visibility and OpacityIn this lesson, we will learn the concept of CSS opacity, what it is, and how to use it in your web development projects.
CSS opacity Property
The CSS opacity property allows you to control the transparency of an element on a web page. It's like adjusting the transparency of a glass pane. The opacity property accepts values between 0 and 1, where 0 means completely transparent (invisible), and 1 means fully opaque (not transparent at all).
Note: Applying the opacity property to a parent element also affects its child elements by making them inherit the same level of transparency.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CSS opacity Example</title>
<!-- Internal CSS -->
<style>
.container {
width: 200px;
height: 200px;
background-image: url("teddybear.png");
background-repeat: no-repeat;
background-size: contain;
background-position: center center;
font-size: 22px;
}
.transparent-box {
width: 200px;
height: 200px;
background-color: black;
opacity: 0.35; /* Set the opacity to 35% */
}
.text {
color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<div class="transparent-box">
<p class="text">Hello, I'm text inside a transparent box!</p>
</div>
</div>
</body>
</html>
In the above example, we have a black box with an opacity of 0.35. This means the box is semi-transparent, allowing the background to show through. You can adjust the opacity value to make the element more or less transparent. You have also noticed that its child element (text paragraph) has also become transparent.
Making background transparent without effecting child elements
You can use the rgba() color code with the CSS background-color property to set the background color transparency of a parent element without effecting the transparency of its child element.
You can also use the rgba() color code with the CSS color property to set the color transparency of a text.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CSS opacity Example</title>
<!-- Internal CSS -->
<style>
.container {
width: 200px;
height: 200px;
background-image: url("teddybear.png");
background-repeat: no-repeat;
background-size: contain;
background-position: center center;
font-size: 22px;
}
.transparent-box {
width: 200px;
height: 200px;
background-color: rgba(0, 0, 0, 0.35);
}
.text {
color: yellow;
font-weight: bold;
}
.transparent-text {
color: rgba(228, 255, 0, 0.40);;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<div class="transparent-box">
<p class="text">Hello, I'm text inside a transparent box!</p>
<p class="transparent-text">Hello, I'm a transparent text inside a transparent box!</p>
</div>
</div>
</body>
</html>