css - opacity

CSS opacity allows you to control the transparency of HTML elements, enabling you to create visual effects like fading, overlays, and background transparency. Opacity values range from 0 (fully transparent) to 1 (fully opaque).

This guide covers:

Basic Usage of Opacity

Hover Effects with Opacity

Applying Opacity to Backgrounds

Overlaying Text with Opacity

1. Basic Usage of Opacity

The opacity property is applied to an element to make it partially or fully transparent.

Syntax

element {

    opacity: value; /* Value between 0 and 1 */

}

opacity: 1 – Fully opaque (default).

opacity: 0.5 – 50% transparent.

opacity: 0 – Fully transparent.

Example

img {

    opacity: 0.7; /* Makes the image 70% visible */

}

In this example, the image will be semi-transparent, showing only 70% of its original opacity.

2. Hover Effects with Opacity

Using opacity with the :hover pseudo-class creates smooth hover effects. This is particularly useful for images, buttons, or cards.

Example

button {

    opacity: 0.8;

    transition: opacity 0.3s ease;

}

button:hover {

    opacity: 1; /* Fully opaque on hover */

}

Here, the button appears slightly transparent by default and becomes fully opaque when hovered, creating a subtle effect.

3. Applying Opacity to Backgrounds

If you want only the background to be transparent while keeping the content fully visible, use an rgba (red-green-blue-alpha) color, where the alpha value controls transparency. The opacity property affects the entire element, including text and other children, but rgba only applies to the background.

Example

div {

    background-color: rgba(0, 128, 255, 0.5); /* 50% transparent blue background */

    padding: 20px;

    color: #000;

}

This example creates a semi-transparent blue background with fully visible content, as only the background is transparent.

4. Overlaying Text with Opacity

Combining opacity with positioning allows you to overlay text on images or other elements for various effects.

Example

<div class="image-container">

    <img src="example.jpg" alt="Example Image">

    <div class="overlay">

        <p>Sample Text</p>

    </div>

</div>

CSS Code

.image-container {

    position: relative;

}

.image-container img {

    width: 100%;

    opacity: 0.8; /* Slightly transparent image */

}

.overlay {

    position: absolute;

    top: 0;

    left: 0;

    width: 100%;

    height: 100%;

    background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent black overlay */

    color: #fff;

    display: flex;

    justify-content: center;

    align-items: center;

    font-size: 24px;

    opacity: 0;

    transition: opacity 0.3s ease;

}

.image-container:hover .overlay {

    opacity: 1; /* Fully visible overlay on hover */

}

In this example:

The image is semi-transparent, and a black overlay with text appears when the user hovers over it.

The text becomes visible by changing the overlay’s opacity on hover.