Transparency in CSS
Problem
On a web page an HTML element is placed on another and the first one wish to look and feel transparent.
Solution
The CSS has a declaration called opacity.
Example
We have an example HTML page with solid background color and a button placed on that.
HTML
<html DOCTYPE!>
<head>
<style>
#main {
background-color: yellow;
height: 100%;
}
</style>
</head>
<body>
<div id="main">
<input type="button" id="btnTransparent" value="Test"/>
</div>
</body>
</html>
The code looks like this:
Now, let’s make the button transparent. We will select it by it’s id: btnTransparent and add some transparency.
#btnTransparent {
opacity: .5;
}
Put the code together:
<html DOCTYPE!>
<head>
<style>
#main {
background-color: yellow;
height: 100%;
}
#btnTransparent {
opacity: .5;
}
</style>
</head>
<body>
<div id="main">
<input type="button" id="btnTransparent" value="Test"/>
</div>
</body>
</html>
It looks like this:
The Test button appears half transparent as set by opacity: .5; It accepts a value from 0 to 1 meaning 0 is full transparent, not visible.
Let’s now add a pseudo element on the button, when the mouse hovers the button, the opacity returns to full.
This would do the trick
#btnTransparent:hover {
opacity: 1;
}
And the complete code:
<html DOCTYPE!>
<head>
<style>
#main {
background-color: yellow;
height: 100%;
}
#btnTransparent {
opacity: .5;
}
#btnTransparent:hover{
opacity: 1;
}
</style>
</head>
<body>
<div id="main">
<input type="button" id="btnTransparent" value="Test"/>
</div>
</body>
</html>
Result
Now, let’s put it all together with a nice background image as follows:
<html DOCTYPE!>
<head>
<style>
* {
margin: 0;
padding: 0;
}
#title_area{
position: absolute;
top: 200px;
left: 50px;
width: 350px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
background-color: sandybrown;
opacity: .5;
}
</style>
</head>
<body>
<div id="title_area"><h3>
<h3>Transparent or not transparent<h3/>
</div>
<img src="background.jpg" width="500" height="600"/>
</body>
</html>
Result
Background image taken from here
Conclusion
Pretty neat. A simple CSS declaration changes the look and feel of the UI.