Overview
The opacity of an element can be used to create effects such as elements fading in our out on hover, or changing opacity as a visual cue to the user.
Note
The following are basic examples. Towards the bottom of this page you’ll find a complete list of all applicable properties, where you can find more information on the properties discussed, and sometimes find more involved properties not discussed on this page.
The transparency can be set, where 1 is opaque and 0 is transparent. Any value in between will give partial transparency. The following is 50% transparent.
div {
background: red;
opacity: 0.5;
}
Note
Opacity will affect anything within the element the property is applied to. For instance, if you have text inside an element with the opacity set low, the text opacity will also be affected.
Hover Effect
Opacity is most often used as a hover effect, such as changing the opacity of an image or image link on hover.
In the following example, when the user hovers the cursor over the image element, the image will show at a lower opacity. This is often used as a cue that the image can be clicked to show a larger version.
img:hover {
opacity 0.5;
}
To make the transition between completely opaque and partially opaque, the transition property can be used. By setting a transition (on the element without the hover), the following will change the opacity over 0.4 seconds making it more pleasing to the eye.
img {
transition: opacity 0.4s;
}
img:hover {
opacity 0.5;
}
Properties
- CSS – opacity PropertyThe opacity property describes the transparency level, where 1 is opaque and 0 is transparent. Any value in between will give partial transparency.
- CSS – transition PropertyThe transition property is a shorthand property for transition-property, transition-duration, transition-timing-function, and transition-delay.
CSS Notes:
- The “inherit”, “initial” and “unset” keywords can be used with any CSS property to set its value
- In CSS there are many ways to express a color value in a property
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.