DEV Community

Cover image for CSS Display None Vs Visibility Hidden
Stanley
Stanley

Posted on

CSS Display None Vs Visibility Hidden

When it comes to manipulating the visibility of elements on a web page using CSS, two commonly used properties are display and visibility. While both can be used to hide elements, they work in different ways and have distinct use cases. In this blog post, we will explore the differences between display: none and visibility: hidden, along with code samples to illustrate their behavior.

display: none

The display: none property is a powerful tool for completely removing an element from the layout of the web page. When applied to an element, it not only makes the element invisible but also removes it from the document flow. This means that the element takes up no space, and surrounding elements act as if it doesn't exist.

Here's a simple example:

Image description

In this example, the element with the class hidden-element is completely removed from the page's layout, and the other elements flow as if it's not there.

visibility: hidden

On the other hand, the visibility: hidden property hides an element while still occupying the same space it would if it were visible. This means that the hidden element is still part of the layout, and it affects the positioning of other elements around it.

Here's an example:

Image description

In this case, the element with the class hidden-element is hidden, but it still occupies space in the layout, affecting the position of the visible elements around it.

When to Use Each

Now that we understand the differences between display: none and visibility: hidden, let's discuss when to use each property.
Use display: none when you want to completely remove an element from the layout, and you don't want it to affect the space occupied by other elements. This is useful when you want to toggle the visibility of an element dynamically, such as in a drop-down menu.
Use visibility: hidden when you want to hide an element but still reserve its space in the layout. This is often used when you want to show and hide elements with animations or transitions, and you need the layout to remain stable.

As I conclude, display: none and visibility: hidden are both valuable tools for controlling the visibility of elements in CSS, but they serve different purposes. Understanding their differences and knowing when to use each property is crucial for creating responsive and visually appealing web designs.

Top comments (0)