Web Development

Control element placement with CSS stacking


Positioning elements on a Web page with CSS has many caveats. One interesting scenario crops up when you need one element to appear where another element is already located. The issue is easily resolved using the z-index CSS feature to control the stacking of elements. This post offers a closer look at CSS stacking elements.

Positioning

Working with the stacking order of elements depends upon the positioning aspects of CSS. There are three positioning options: relative, absolute, and fixed.

  • Relative: Positioned elements are shifted through the use of side-offset properties. When an item is relatively positioned, it creates a new containing block for any of its children. This block corresponds to where the element has been positioned. This allows you to position an element relative to its parent, which has already been positioned.
  • Absolute: When elements are positioned absolutely, they are completely removed from the flow of other elements on the page; that is, they are positioned with respect to their containing block. The edges are placed using the side-offset properties. Absolutely-positioned elements do not flow around other elements and other elements do not flow around them. Thus, an absolute element may appear to overlap other elements.
  • Fixed: The fixed positioning of elements resembles the absolute model, but fixed elements are completely removed from the document with no position relative to any other element on the document. Using fixed positioning, you can create interfaces that resemble HTML frames using only CSS.

You specify offset values for positioning elements. These offset values are specified using a combination of the top, right, left, and bottom style properties. The value of each is interpreted as the distance the box's corresponding outer edge should be moved with respect to its original position in the normal flow.

In Listing A, the example Web page combines relative and absolute positioning. The page is divided horizontally into three regions using absolute positioning and percentage values. Text is placed within each section using relative positioning. (Here's a link to Listing A if you want to copy and paste the code.)

<html><head>

<title>CSS Positioning </title>

<style>

DIV#top {position:fixed;top:0;bottom:20%;left:0;right:90%;background:yellow;height:20%;margin:0;}

DIV#middle {position:fixed;top:21%;bottom:80%;left:0;right:90%;background:gray;height:60%;margin:0;}

DIV#bottom {position:fixed;top:81%;bottom:90%;left:0;right:90%;background:yellow;height:20%;margin:0;}

.title{position:relative;left:25%;top:10%;bottom:5%;right:90%;font-size:20pt;}

</style></head><body>

<div id="top">

<div class="title">This is a test</div>

</div>

<div id="middle">

<div class="title">Place some text here.</div>

</div>

<div id="bottom">

<div class="title">Thanks for visiting!</title>

</div>

</body></html>

When placing multiple items on a page using CSS positioning, there will inevitably be situations where two or more elements occupy the same area of a page.

Stacking

The overlap of elements may be by accident or by design. If it is by design, one of the elements should take precedence over the others and display on top. This is where the z-index setting enters the picture. (If you remember your days in geometry class, the z-index is the z-axis when placing elements in 3-dimensional space.)

You should think of layers when developing Web applications using CSS positioning; that is, elements appear on the page stacked or in layers. The z-index defines where the element appears in the stack. The system places the last item on top if no z-index values are specified.

You can override this default behavior by including a z-index with the positioned elements. The z-index value is an integer with the higher integer value coming out on top when items are stacked. Also, you may assign the same z-index value to two elements. If these elements are stacked, they will display in the order they are written in the HTML, with the last element on top. That is, they utilize the default behavior.

In addition, negative values can be specified for z-index. An element with a negative value is displayed behind any value with an undefined or positive z-index value in the same stacking context. However, negative z-index values are not properly handled by all browsers, as Internet Explorer 5.5 and Opera 5 do not support it.

Listing B includes an image, text, and a hyperlink. The image has a z-index value of 1, while the text is assigned a value of 100, so the text will always appear above the image in the stack. In this example, the text appears on top of the image. The link has a z-index value of 0, so it is below both the text and the image in the stack. Given the left and top margin values of the links, only half of the link is visible as a portion of it is behind the image due to the stacking order. (Here's a link to Listing B if you want to copy and paste the code.)

<html><head>

<style type="text/css">

.trlogo { position:absolute; left:0px; top:0px; z-index:1; width: 200; height: 100; }

.header {position: absolute; left:0;top:5;z-index:100;font-size: 20pt; font-face:Arial;font-weight:bold;color: red; }

.link {position: absolute; left:75;top:50;z-index:0;font-size: 10pt; font-face:Arial;font-weight:bold; }

</style></head>

<body>

<p class="header">Thanks for reading.</p>

<img class="trlogo" src="http://b2b.cbsimg.net/images/200608/logo.gif" mce_src="http://b2b.cbsimg.net/images/200608/logo.gif">

<a href="http://www.techrepublic.com/1200-3513-5737146.html" mce_href="http://www.techrepublic.com/1200-3513-5737146.html" class="link">Web

Development Newsletter Archive</a>

</body></html>

The myriad of scenarios possible with positioning and stacking can be overwhelming when faced with multiple elements on a page. The W3C lays out how to evaluate elements.

Controlling page layout

When using the positional features of CSS, the z-index value allows you to control which elements take precedence and which ones are fully visible when/if elements overlap. By default, the last item takes precedence, but you can assign your own integer values with the largest value ending up on top. Be sure to test and validate your CSS in all target browsers.

Do you utilize CSS positioning and stacking in your Web applications? Share your CSS tips and experience with the Web development community.

Check out the Web Development Zone archive, and catch up on the most recent editions of Tony Patton's column.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

---------------------------------------------------------------------------------------

Get weekly development tips in your inbox Keep your developer skills sharp by signing up for TechRepublic's free Web Development Zone newsletter, delivered each Tuesday. Automatically subscribe today!

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

5 comments
aspatton
aspatton

I appreciate the valuable feedback. The z-index feature is supported in IE 4.0+, Netscape 4.0+, Opera 3.5+ and so forth, but of course it doesn't properly work in these and other browsers. All future articles will include a section that highlights browser support.

mosw
mosw

I did a quick test of your examples in FireFox and IE 6. They seemed to work as described in IE 6 but not Firefox which leads me to these questions: - How broad is the browser support for these festures? - Is browser treatment affected by the doctype declaration or some other coding issue? CSS has been around a while now and I always get my hopes up whenever I see a description of how is it supposed to work then find myself spending hours tracking down browser quirks. I appreciate these articles as they are causing me to revisit features of CSS that I had given up on in the past. I would recommend though that any article on CSS needs to make some statement about browser support. It would be good enough for me if you simply stated in which browsers you have experience or tested this CSS feature with. Where you don't know, maybe ask for readers comments on browser support experience. Thanks for the article.

zetacon4
zetacon4

to provide some CSS instructions. The study of how CSS works in different browsers is a complicated topic all its own. I have taken the time to study and proof out many style methods in the major browsers. Let me tell you, doing correct styling for all browsers in one style document is nearly impossible. My solution has been to detect what browser the visitor is using, then send the appropriate stylesheet to them. This has solved many a headache. I have also developed a theme style database that maintains all colors and other theme values. I can update all the browser stylesheets anytime a change to the theme values are made.

alan.shryock
alan.shryock

I was surprised a valid DTD statement wasn't provided as that can have considerable impact how a page is rendered by different browsers using quirks mode. Using 4.01 transitional and strict, IE7 rendering is consistent with Firefox 2, which I don't believe is what the authors were aiming for. I think the rendering with IE6 is what they intend the page to look like. I find CSS quite confusing, yet very interesting and always look for better ways of building web pages. Unfortunately, this example doesn't fill in the gaps it attempts to address.

Scuffer
Scuffer

I know this article just scratches the surface of a complex and often frustrating subject, but I would assume TechRepublic would give us cross browser examples, or point out those nagging differences in browser support. Except for the note about negative Z values, this article does neither. Listing A does not work properly in Firefox, but listing B does.