The CSS filter
property applies graphical effects like blur or color shifting to an element. The opacity()
function within the filter
property controls the transparency of an element. A value of 0% makes the element completely transparent, while 100% makes it fully opaque.
Example 1: Basic Opacity
.element-basic-opacity {
/* Applies a 50% opacity to the element */
filter: opacity(50%);
}
Explanation This code selects an element with the class .element-basic-opacity
and reduces its opacity by half. This makes the element see-through, allowing any content behind it to be partially visible.
Example 2: Opacity on Hover
.element-hover-opacity {
transition: filter 0.3s ease-in-out; /* Smooth transition for the filter effect */
}
.element-hover-opacity:hover {
/* Makes the element fully transparent on hover */
filter: opacity(0%);
}
Explanation This example makes an element with the class .element-hover-opacity
completely disappear when the user hovers their mouse over it. The transition
property ensures the change in opacity is smooth.
Example 3: Decimal Value Opacity
.element-decimal-opacity {
/* Applies a 25% opacity using a decimal value */
filter: opacity(0.25);
}
Explanation The opacity()
function also accepts decimal values between 0 and 1. In this case, 0.25
is equivalent to 25%
, making the element with the class .element-decimal-opacity
mostly transparent.
Example 4: Fully Opaque
.element-full-opacity {
/* This is the default state, making the element fully visible */
filter: opacity(1);
}
Explanation Setting opacity()
to 1
or 100%
renders the element completely opaque, which is the default appearance. This can be useful for resetting an element's opacity on a specific interaction.
Example 5: Opacity on an Image
.image-opacity {
width: 200px;
/* Applies a 70% opacity to an image */
filter: opacity(70%);
}
Explanation This CSS rule targets an image and applies a 70%
opacity. This technique is often used to create subtle, faded image effects or to overlay text on a less distracting background image.
Example 6: Combining with Other Filters
.element-combined-filter {
/* First applies a grayscale effect, then sets opacity to 60% */
filter: grayscale(100%) opacity(60%);
}
Explanation The filter
property allows for chaining multiple filter functions. This code first converts the element to grayscale and then applies a 60%
opacity, creating a more complex visual effect.
Example 7: Opacity within a Parent Element
.parent-element:hover .child-element {
/* Child becomes 30% opaque when hovering over the parent */
filter: opacity(0.3);
transition: filter 0.5s; /* Adds a smooth transition effect */
}
Explanation This example demonstrates how to change the opacity of a child element when a user interacts with its parent. When hovering over .parent-element
, the .child-element
within it fades to 30%
opacity.