Techie Tip of the Week – CSS: Hiding Content using display:none vs. visibility:hidden

Using Cascading Style Sheets, there are two different ways you can hide objects from view — visibility: hidden; and display: none;

  • With the display: none; declaration, elements are removed from view and take up no space. When you use this declaration, it is as if the elements were never placed on the web page.
  • With the visibility: hidden; declaration, elements are merely hidden from view. They still occupy the same place that they originally would have taken up.

In this week’s tip, we’ll explore the differences between the two.


Example — Neither display:none nor visibility:hidden

This is the original web page, with 3 flowers — Dandelion, Spiked, and Sunflower. To produce this web page:

3 flowers

The HTML and CSS code are:

<!DOCTYPE HTML>
<html>
<head>
<title>Flowers</title>
<style type="text/css">
.hidden { visibility: hidden; }
.nodisplay { display: none; }
</style>
</head>
<body>
 <img src="Dandelion.gif" />
 <img src="Spiked.gif" />
 <img src="Sunflower.gif" />
</body>
</html>

Example — display:none;

In this example, we will use display:none; to remove the Spiked flower. Note that it is as if the Spiked flower never existed. To produce this web page:

2 flowers - just Dandelion and Sunflower

The HTML and CSS code are:

<!DOCTYPE HTML>
<html>
<head>
<title>Flowers</title>
<style type="text/css">
.hidden { visibility: hidden; }
.nodisplay { display: none; }
</style>
</head>
<body>
 <img src="Dandelion.gif" />
 <img src="Spiked.gif" class="nodisplay" />
 <img src="Sunflower.gif" />
</body>
</html>

Example — visibility:hidden;

In this example, we will use visibility:hidden; to remove the Spiked flower. Note that the space that the Spiked flower would have taken up remains — but it’s empty. To produce this web page:

2 flowers -- Dandelion with a space the size of Spiked followed by the Sunflower

The HTML and CSS code are:

<!DOCTYPE HTML>
<html>
<head>
<title>Flowers</title>
<style type="text/css">
.hidden { visibility: hidden; }
.nodisplay { display: none; }
</style>
</head>
<body>
 <img src="Dandelion.gif" />
 <img src="Spiked.gif" class="hidden" />
 <img src="Sunflower.gif" />
</body>
</html>

Tags: ,

Leave a Reply

You must be logged in to post a comment.