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

 

visibility:hidden and display:none are both CSS properties that can be used to hide elements on a web page, but they work in slightly different ways:

  1. visibility:hidden:
    • When you apply visibility:hidden to an element, the element is hidden from view, but it still takes up space in the layout as if it were visible.
    • It doesn't affect the layout of other elements around it, so the hidden element's space is preserved.
    • Hidden elements can still be interacted with using JavaScript or other means, and they can still affect the layout of other elements if they have properties like margins or padding.

Example:

HTML:

html
<div class="hidden-element">This is a hidden element.</div> <div>This is some content.</div>

CSS:

css
.hidden-element { visibility: hidden; }

In this example, the "hidden-element" is not visible, but it still occupies space in the layout.

  1. display:none:
    • When you apply display:none to an element, the element is completely removed from the layout, and it does not take up any space on the page.
    • It also hides the element from view, but it has a more significant impact on the layout because other elements will adjust as if the hidden element doesn't exist.
    • Like visibility:hidden, you can still manipulate elements with display:none using JavaScript, but they won't affect the layout of other elements.

Example:

HTML:

html
<div class="hidden-element">This is a hidden element.</div> <div>This is some content.</div>

CSS:

css
.hidden-element { display: none; }

In this example, the "hidden-element" is not visible, and it doesn't take up any space in the layout. The content below it moves up to fill the space.

In summary, the key difference is that visibility:hidden hides an element while preserving its layout space, whereas display:none hides an element and removes it from the layout entirely. The choice between the two depends on your specific design and layout requirements.

Comments