Difference between display:none and visibility:hidden in CSS. Hide content in HTML through CSS using visibility and display properties

Introduction: In a Web Page we can hide an HTML element from being displayed using two ways that is by setting the display property to none or by setting the visibility property to hidden in CSS.

In this post we will explore the difference between the two

When we hide an element using visibility property,it will cause the space to be unused that is the space will be preserved as it is i.e. there will be a blank/empty space.

Whereas when hiding an element using the display property will cause the space to be used by other elements.

Example: 

Code explaining the difference
<head>
       <title>Hiding Elements</title>
</head>
<html>
    <body>
       <script type="text/javascript">
           function hideSampleText1() {
               document.getElementById('Text1').style.visibility = 'hidden';
           }
           function showSampleText1() {
               document.getElementById('Text1').style.visibility = 'visible';
           }
           function hideSampleText2() {
               document.getElementById('Text2').style.display = 'none';
           }
           function showSampleText2() {
               document.getElementById('Text2').style.display = 'block';
           }
       </script>
       <h1 id="Text1">Hide using Visibility</h1><hr>
       <h1 id="Text2">Hide using Display</h1><hr>
       Using Visibility:<br/>
       <button onclick="hideSampleText1()">Hide Text 1</button>
       <button onclick="showSampleText1()">Show Text 1</button> <br/> <br/>
       Using Display:<br/>
       <button onclick="hideSampleText2()">Hide Text 2</button>
       <button onclick="showSampleText2()">Show Text 2</button>
    </body>
</html>



Screenshot below shows the initial loaded page when all are enabled


Screenshot below shows when Hide Text 1 button is clicked,  "Hide Text 1" button contains code to hide the text label Text 1 which has the text "Hide using Visiblity" using visibilty property

Here it can be seen that once "Hide Text 1" button is clicked the text "Hide using Visibility" is not visible and space occupied by the Text has been preserved as it is


Screenshot below shows when Hide Text 2 button is clicked,  "Hide Text 2" button contains code to hide the text label Text 1 which has the text "Hide using Visiblity" using display property

Here it can be seen that once "Hide Text 2" button is clicked the text "Hide using Display" is not visible and space occupied by the Text has not been preserved as it is and blank space has appeared.


Uses:


Links: