The opacity
property defines the transparency of an element.
It specifies how much of the background is visible through the element.
Opacity values range from 0 (transparent) to 1 (opaque).
A transparent image with an opacity
value of 0.5.
<div>
<img style="opacity: 0.5;"
src="/img/css/cardplayers.jpg" />
</div>
Valid opacity
values range from 0 - 1, or 0% - 100%.
A value of 0 makes the element transparent (i.e. invisible).
A value of 0.5 makes it see-through.
And a value of 1 displays the element normal.
opacity: number | initial | inherit;
Value | Description |
---|---|
number |
Sets opacity from 0 - 1, or 0% - 100%. |
initial |
Sets the value to its default value. |
inherit |
Inherits the value from its parent element. |
This element and its children have an opacity of 20%.
Displays the div element and its children with 20% opacity
<div style="opacity: 20%">
<img src="/img/css/cardplayers.jpg" />
<p>
Displays the div element and
its children with 20% opacity
</p>
</div>
Using RGBA color to set the background color and opacity.
<style>
.bg-1 { background: rgba(70, 130, 180, 0.1); padding: 25px; }
.bg-2 { background: rgba(70, 130, 180, 0.5); padding: 25px; }
.bg-3 { background: rgba(70, 130, 180, 0.9); padding: 25px; }
</style>
<div class="bg-1">
A background color with 10% opacity
</div>
<div class="bg-2">
A background color with 50% opacity
</div>
<div class="bg-3">
A background color with 90% opacity
</div>
Setting an element's opacity with JavaScript.
Select a dropdown value to change the image opacity.
<img src="/img/css/cardplayers.jpg"
id="image-opacity">
<p>Select a dropdown value
to change the image opacity.
</p>
<select onchange="setOpacity(this.value);">
<option selected="selected" value="1">100%</option>
<option value="0.8">80%</option>
<option value="0.5">50%</option>
<option value="0.3">30%</option>
<option value="0">0%</option>
</select>
<script>
let setOpacity = opacity => {
document.getElementById("image-opacity")
.style.opacity = opacity;
}
</script>
Hovering over the image will transition opacity from 20% to 100%.
<style>
.transition-img {
opacity: 0.2;
transition: 0.5s ease;
}
.transition-img:hover {
opacity: 1;
}
</style>
<div>
<img src="/img/css/cardplayers.jpg"
class="transition-img" />
</div>
This table shows when opacity
support started for each browser.
Chrome
|
4.0 | Jan 2010 |
Firefox
|
2.0 | Jan 2010 |
IE/Edge
|
9.0 | Mar 2011 |
Opera
|
9.0 | Jun 2006 |
Safari
|
3.1 | Mar 2008 |