乐闻世界logo
搜索文章和话题

What is the difference between visibility:hidden and display: none ?

1个答案

1

In CSS, both visibility: hidden; and display: none; can be used to hide elements, but they function differently and are applicable in distinct scenarios.

1. Space Occupation Differences

visibility: hidden; makes the element invisible while still reserving its space in the layout. Once hidden, the space it occupies remains unchanged, meaning other elements maintain their original positions without shifting.

Example: Suppose there is a list where one item is set to visibility: hidden;. Although this item is invisible, the other items in the list retain their original spacing.

html
<ul> <li>Item 1</li> <li style="visibility: hidden;">Item 2</li> <li>Item 3</li> </ul>

display: none; not only hides the element but also removes it entirely from the document flow, effectively making it as if it were deleted from the HTML. This affects the overall layout, causing surrounding elements to shift.

Example: Similarly, for the list above, if one item is set to display: none;, it becomes invisible and the space it occupied vanishes, causing the other items to shift closer together.

html
<ul> <li>Item 1</li> <li style="display: none;">Item 2</li> <li>Item 3</li> </ul>

2. Impact on Child Elements

When an element is set to visibility: hidden;, its child elements can be made visible by explicitly setting visibility: visible; because the visibility property is inherited.

Example:

html
<div style="visibility: hidden;"> <p>This text is invisible.</p> <p style="visibility: visible;">This text is visible.</p> </div>

In the above example, even though the parent element is hidden, child elements can still be made visible by setting visibility: visible;.

However, for display: none;, the effect on child elements is complete; regardless of settings like display: block; or other display properties, child elements cannot be rendered.

3. Performance Considerations

display: none; is generally more efficient in performance than visibility: hidden; because the latter still requires the browser to perform layout calculations (though it skips rendering). When frequent toggling of element visibility is not required, display: none; is the better choice.

In summary, the choice between visibility: hidden; and display: none; depends on specific requirements, such as whether the element needs to remain in the document flow and whether independent control over child elements' visibility is necessary.

2024年6月29日 12:07 回复

你的答案