Display none
The display: none value is used to completely hide an element from the document. It is the most powerful way to remove an element, as it makes the element invisible and removes it from the layout flow entirely.
Key Characteristics of display: none
1. Zero Space, Zero Presence
The element is treated as if it does not exist in the document structure.
- Layout: It consumes no space on the page. All surrounding elements collapse into the space where the hidden element would have been.
- Rendering: It is not drawn or rendered by the browser.
2. Not Interactive
Any element set to display: none cannot be interacted with.
- Events: It does not receive mouse clicks or keyboard focus events.
- Accessibility: It is completely ignored by screen readers and other assistive technologies.
3. Hides Children
The display: none property affects the element itself and all of its descendant elements. If a parent is set to display: none, none of its children will be visible or present in the layout, regardless of their own display properties.
display: none vs. visibility: hidden
It is important to understand the difference between hiding an element with display: none and hiding it with visibility: hidden.
| Feature | display: none | visibility: hidden |
|---|---|---|
| Layout Space | Removes space. Surrounding elements shift to fill the gap. | Reserves space. Element is invisible, but its box still occupies its dimensions. |
| Interactions | Not interactive. | Not interactive (cannot be clicked). |
| Accessibility | Ignored by screen readers. | Can sometimes be read by screen readers (behavior varies). |
| Best Use | Dynamically hiding content (e.g., a modal or dropdown menu) that is not currently needed. | Temporarily hiding content while maintaining layout structure (e.g., a column in a table). |
Practical Use Cases
1. Toggling UI Elements (JavaScript)
The most common use is to toggle the visibility of complex components in response to user actions (e.g., clicking a hamburger menu icon).
/* Start the modal hidden */
.modal {
display: none;
}
/* Show the modal when the 'active' class is added by JavaScript */
.modal.active {
display: block;
}
2. Responsive Hiding
Using media queries to hide large blocks of content that are irrelevant or too cluttered on small screens.
/* Hide a specific sidebar column entirely on small screens */
@media (max-width: 768px) {
.sidebar-ads {
display: none;
}
}
Interactive display: none Demo
Click the "Toggle Visibility" button below. When the element is hidden using display: none, notice how the container shrinks and the text wraps directly from the paragraph above to the paragraph below, demonstrating that the space is fully reclaimed.