devxlogo

CSS Properties: Display vs. Visibility

CSS Properties: Display vs. Visibility

Browsers Targeted: Internet Explorer 3+

It’s fairly easy to confuse the Cascading Style Sheets (CSS) properties display and visibility, because it would seem that they do much the same thing. However, the two properties are in fact quite different. The visibility property determines whether a given element is visible or not (visibility=”visible|hidden”). However, when visibility is set to hidden, the element being hidden still occupies its same place in the layout of the page.

 
 
This example displays text that toggles between a visibility of 'visible' and 'hidden'. Note the behavior of the next line.
This second line shouldn't move, since visibility retains its position in the flow
This example displays text that toggles between a visibility of ‘visible’ and ‘hidden’. Note the behavior of the next line.
This second line shouldn’t move, since visibility retains its position in the flow

Note that when an item is hidden, it doesn’t receive events. Thus in the sample code, the first sentence never detects that there has been a mouse click once the item is hidden, so you can’t click the area to make it visible again. The display property, on the other hand, works a little differently. Where visibility hides the element but keeps its flow position, display actually sets the flow characteristic of the element. When display is set to block, for example, everything within the containing element is treated as a separate block and is dropped into the flow at that point as if it were a

element (you can actually set the display block of a element and it will act like a
. Setting the display to inline will make the element act as an inline element?it will be composed into the output flow as if it were a >, even if it were normally a block element such as a
. Finally, if the display property is set to none, then the element is actually removed from the flow completely, and any following elements move forward to compensate:
 
 
Click on the blue text to see how it affects the flow.
Click on the blue text to see how it affects the flow.

Notice that if the display property is not explicitly set, it defaults to the display type the element normally has. Of the two, the display property is definitely the more useful, as most instances of needing to hide text also involve shifting the surrounding HTML flow to accommodate it (think tree structures, as an example).

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist