CSS Visibility, Opacity
Hide or fade content while understanding its effect on layout and interaction.
CSS provides the visibility and opacity properties to control whether an element can be seen. Although both can hide content, they work differently.
- visibility controls whether an element is visible.
- opacity controls how transparent an element appears.
- Both properties keep the element's space in the layout.
The visibility Property
The visibility property shows or hides an element without removing its space.
.notice {
visibility: hidden;
}The notice becomes invisible, but the browser keeps its original space on the page.
Common values include:
- visible – displays the element normally
- hidden – hides the element but keeps its space
- collapse – mainly hides table rows or columns
.notice {
visibility: visible;
}Use visibility: hidden when you want to hide something without changing the surrounding layout.
The opacity Property
The opacity property controls an element's transparency. It accepts values from 0 to 1.
.image {
opacity: 0.5;
}Common values include:
- 1 – completely visible
- 0.5 – partly transparent
- 0 – completely transparent
.card {
opacity: 0;
}The card cannot be seen, but it still occupies space.
Opacity also affects an element's children:
.card {
opacity: 0.5;
}If the card contains text and images, they also become partly transparent.
Visibility, Opacity, and Display
These properties hide elements in different ways:
.first {
visibility: hidden;
}
.second {
opacity: 0;
}
.third {
display: none;
}- visibility: hidden hides the element and keeps its space.
- opacity: 0 makes it transparent and keeps its space.
- display: none removes the element from the layout.
An element with opacity: 0 can still receive clicks and keyboard focus. This may confuse users.
.hidden-button {
opacity: 0;
pointer-events: none;
}The pointer-events: none declaration prevents mouse interaction, but keyboard behaviour may require additional handling.
Creating Hover Effects
Opacity is commonly used for smooth hover effects:
.image {
opacity: 0.7;
transition: opacity 0.3s;
}
.image:hover {
opacity: 1;
}The image becomes fully visible when the user moves the pointer over it.
Using Transparent Colours
To make only the background transparent, use a colour with an alpha value instead of applying opacity to the entire element:
.message {
background-color: rgba(31, 78, 216, 0.5);
}This keeps the message text fully visible while making its background transparent.