[ Team LiB ] Previous Section Next Section

12.7 Hiding and Showing Elements

NN 6, IE 5

12.7.1 Problem

You want to hide a currently visible element or show a currently hidden element.

12.7.2 Solution

Two CSS style properties (and their corresponding scripted properties) influence the visibility of an element, but your choice of usage has a big impact on the results of showing or hiding an element. The less-intrusive property is style.visibility, whose fully supported values are hidden, inherit, or visible, as in the following example that hides an element:

document.getElementById("warning").style.visibility = "hidden";

Changing this value has no affect on surrounding content. The other relevant property, style.display, when set to none, removes the element from rendering flow of the page, forcing surrounding content to cinch up to fill the space formerly occupied by the element:

document.getElementById("warning").style.display = "none";

Restoring the display property value to its applicable display mode (typically block or inline) reinserts the element into rendering flow, and the content adjusts itself to accommodate the inserted content.

12.7.3 Discussion

CSS property inheritance plays a significant role in the resulting effect of your hiding and showing of elements. The default visibility property value is inherit, which means that an element's visibility is governed by its parent containing element. Therefore, if you hide a container, all nested elements are hidden as well. But each element can also be the master of its own visibility in most, but not all, browsers. For example, in Netscape 6, if you set the visibility of a container element to hidden and one of the container's children to visible, the child element will be visible even though its parent is not.

By and large, the visibility style property is most reliably used on either block-level elements or absolute-positioned elements. In fact, the property is even modifiable for absolute-positioned div or span elements in Netscape 4 (as well as genuine layer element objects).

Adjusting the display style property is a more substantial act in the eyes of the CSS model. This property has a large range of possible values, some of which are dedicated to the way browsers render tables, table components, and list items. It even has the power to override default element characteristics such that an inline element is treated instead as a block-level element. Therefore, when you set the property to none, the action does far more than just hide the element. You're telling the browser to shrink the element's renderable space to zero height and width, and to adjust the rendering of surrounding elements. The element, however, is not removed from its place in the document node tree.

12.7.4 See Also

Several recipes in Chapter 10 that hide and show elements in dynamic navigation menus.

    [ Team LiB ] Previous Section Next Section