CSS Hide Elements
CSS provides several ways to hide HTML elements. The most common methods are display : none, visibility : hiddens, and opacity: 0.
1. display: none
This is the most common method.
.box { display: none; }
It completely hides the element and removes its space from the page.
Example
<div class="box">Hello World</div> <p>This is a paragraph.</p>
.box { display: none; }
Result: The box disappears, and the paragraph moves into its place.
2. visibility: hidden
.box { visibility: hidden; }
This hides the element, but its space remains.
Before: [ BOX ] [ TEXT ] After: [ ] [ TEXT ] ↑ space remains
This is useful when you want to hide something without changing the layout.
3. opacity: 0
.box { opacity: 0; }
This makes the element completely transparent.
However, unlike display: none, the element still occupies space and can still potentially receive mouse/keyboard interaction.
For a non-interactive invisible element, you might use:
.box { opacity: 0; pointer-events: none; }
4. Hide an Element on Mobile
You can hide an element only on smaller screens using a media query:
@media (max-width: 768px) { .menu { display: none; } }
The .menu will be hidden when the screen width is 768px or less.
5. Hide an Element by ID
HTML:
<div id="advertisement"> Advertisement </div>
CSS:
#advertisement { display: none; }
6. Hide Multiple Elements
You can hide multiple classes at once:
.header, .footer, .sidebar { display: none; }
All three elements will be hidden.
Important Difference
| CSS | Hidden? | Space Removed? |
|---|---|---|
display: none | ✅ Yes | ✅ Yes |
visibility: hidden | ✅ Yes | ❌ No |
opacity: 0 | Visually yes | ❌ No |
Best choice
If you want to completely remove an element from the page layout, use:
display: none;
If you want to hide it but keep its space, use:
visibility: hidden;
If you want to make it transparent, use:
opacity: 0;
Comments
Post a Comment