The opacity property accepts values ranging from 0.0 to 1.0, where lower values indicate higher transparency.
Example
img { opacity: 0.5; } |
The opacity property is commonly utilized alongside the :hover selector to modify the opacity when the mouse is hovered over an element.
Example
img { opacity: 0.5; } img:hover { opacity: 1.0; } |
The initial CSS block resembles the code in Example 1. Additionally, we’ve specified the behavior for when a user hovers over one of the images: the image should maintain full opacity (opacity: 1;) during the hover state.
Once the mouse pointer moves away from the image, the image will return to being transparent.
An instance of a hover effect that behaves in reverse.
Example
img:hover { opacity: 0.5; } |
When employing the opacity property to introduce transparency to an element’s background, all child elements also adopt the same level of transparency. This can result in difficulty reading text within an element that is fully transparent.
Example
div { |
To prevent applying opacity to child elements, as demonstrated in the example above, utilize RGBA color values. The following example illustrates how to set the opacity solely for the background color without affecting the text.
In our CSS Colors Chapter, you’ve discovered that besides RGB, you can employ an RGB color value with an alpha channel (RGBA), which determines the opacity for a color.
An RGBA color value is denoted by: rgba(red, green, blue, alpha), where the alpha parameter ranges from 0.0 (completely transparent) to 1.0 (fully opaque).
Tip: Further insights into RGBA Colors will be provided in our CSS Colors Chapter.
Example
div { |
Example
<html> <head> <style> div.background { background: url(klematis.jpg) repeat; border: 2px solid black; } div.transbox { div.transbox p { </head> <body> <div class=”background”> <div class=”transbox”> <p>This is some text that is placed in the transparent box.</p> </div> </div> </body> </html> |
Initially, we generate a <div> element (class=”background”) featuring a background image and a border.
Subsequently, within the aforementioned <div>, another <div> (class=”transbox”) is established.
The <div class=”transbox”> contains a background color and a border, rendering the div transparent.
Within the transparent <div>, text is enclosed within a <p> element.