The display: none;
and visibility: hidden;
properties in CSS both make elements invisible, but they behave differently in terms of layout and space allocation. Here’s a breakdown of the differences:
1. display: none;
- Effect on Layout: The element is completely removed from the document layout. It no longer takes up any space in the layout, and any surrounding elements will behave as though the element doesn’t exist.
- Use Case: This is often used when you want to completely hide an element and not have it affect the layout at all (e.g., in dropdown menus or dynamic content loading).
- Example:cssCopy
.hidden { display: none; }
With this, the element with the class.hidden
will not appear on the page and will not occupy any space.
2. visibility: hidden;
- Effect on Layout: The element is still rendered in the layout, but it is made invisible. It occupies space in the layout, meaning the surrounding elements will adjust to the presence of the element as if it were still visible.
- Use Case: This is useful when you want to hide an element but still maintain its position in the layout. For example, when you want an element to be hidden temporarily but still keep its space for animation or layout purposes.
- Example:cssCopy
.invisible { visibility: hidden; }
Here, the element with the class.invisible
will not be visible, but it will still take up space and affect the flow of the page.
Summary of Differences:
Feature | display: none; | visibility: hidden; |
---|---|---|
Visibility | The element is completely hidden. | The element is hidden but still takes space. |
Space in Layout | Does not take up any space in the layout. | Takes up space, but is invisible. |
Impact on Flow | Other elements behave as if the element doesn’t exist. | Surrounding elements will not be repositioned. |
Use Case | When you want to completely remove the element from the layout. | When you want the element hidden but still in the layout. |
Quick Example:
htmlCopy<div class="box1">This box will disappear completely (no space).</div>
<div class="box2">This box will be invisible but still take up space.</div>
cssCopy.box1 {
display: none;
}
.box2 {
visibility: hidden;
}
.box1
will not be visible and will also not take up any space..box2
will still take up space but will not be visible.
So, use display: none;
when you need to fully remove an element, and visibility: hidden;
when you want the element to remain in the flow but just be invisible.