Difference between display: none; and visibility: hidden;

CSS properties display and visibility can be used to hide and show elements on the web page.

display: none; 

The display: none property is used to essentially remove an element completely from the document even though it is still there in the code. The hidden element does not take up any space on the page. 

visibility: hidden;

The visibility: hidden property also hides an element, but affects the layout , that is, the element is invisible to the browser but still remains in place and takes up the same space as it would have had it not been hidden.

The example below shows how these properties work.

<!DOCTYPE html>
<html>
   <head>
      <style>
         .h-none{
            display: none;
         }
         .p2, .h-hidden {
            visibility: hidden;
         }
      </style>
   </head>
   <body>
      <h2 class="">Heading one</h2>
      <h3>Subheading one</h3>
      <p class="p1">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Felis bibendum ut tristique et.</p>
      <h2 class="h-none">Heading two</h2>
      <h3>Subheading two</h3>
      <p class="p2">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Felis bibendum ut tristique et.</p>
      <h2>Heading three</h2>
      <h3 class="h-hidden">Subheading three</h3>
      <p class="p3">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Felis bibendum ut tristique et.</p>
   </body>
</html>

When this code is viewed in a web browser, it will appear as shown below.

difference between display none and visibility hidden

From the picture above, “Heading two” is given display: none; therefore does not appear on the page and no space is left where it is supposed to be.

The second paragraph and “subheading three” also do not appear on the page but blank spaces are left to show where these elements are supposed to be.

Display: none is commonly used when making responsive websites where you might want to include some elements in one screen size but not for others using media queries.

Visibility: hidden is used when you don’t want an element visible but you want it to still affect the page for example when creating collapsing dropdown menus.