Using the opacity
Property
The opacity
property sets the opacity level for an element, which affects its transparency. The value ranges from 0
(fully transparent) to 1
(fully opaque).
- Basic Usage
In this example, the .transparent-box
class sets the opacity to 50%, making the element semi-transparent.
.transparent-box { opacity: 0.5; /* 50% transparency */ }
Using RGBA Colors for Transparency
RGBA color values are another way to apply transparency. The a
in rgba
stands for alpha channel, which controls the opacity of the color.
- Basic Usage
In this example, the .transparent-bg
class sets a red background color with 50% transparency.
.transparent-bg { background-color: rgba(255, 0, 0, 0.5); /* Red background with 50% transparency */ }
CSS Opacity and Transperancy Example Code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Opacity and Transparency Example</title> <style> .container { width: 600px; margin: auto; } .transparent-box { width: 200px; height: 200px; background-color: blue; opacity: 0.5; /* 50% transparency */ margin-bottom: 20px; } .transparent-bg { width: 200px; height: 200px; background-color: rgba(255, 0, 0, 0.5); /* Red background with 50% transparency */ } </style> </head> <body> <div class="container"> <div class="transparent-box">This box has 50% opacity.</div> <div class="transparent-bg">This box has a red background with 50% transparency.</div> </div> </body> </html>