That Standards Guy

Z-index: sandwich filler

Working with z-index can be a little counter-intuitive at times.

With my redesign I wanted to place a "polaroid" style photo of myself behind the "about" section but in front of the main content and header. If I hadn't used such large text and a coloured background perhaps I wouldn't even have noticed what was happening.

Here's a snippet of the markup — note that the image is semantically connected to the about section so it follows after the section heading.

<div id="page">
  <div id="header">
    <h1>That Standards Guy</h1>
  </div>
  <div id="content">
    <div id="mainContent">
      <h2>Z-index Stacking Example</h2>
      <p>Pellentesque habitant morbi tristique senectus ...</p>
    </div>
    <div id="secContent">
      <h2>About</h2>
      <img src="imgs/karldawson.jpg" width="200" height="200" alt="Karl" id="polaroid" />
      <p>Pellentesque ...

So what was needed was some straightforward CSS positioning to move the image out of the content flow and place it somewhere off the top-left of the about box. To do this, I first set the <div id="secContent"> container with position: relative then positioned the image like so:

img#polaroid{position:absolute;top:-160px;left:-85px;}

I'm good to go with using z-index now as you can't set it without first setting the position property.

img#polaroid{z-index:-1;position:absolute;top:-160px;left:-85px;}

I think without the blue background on the title I would have said job done, but the image was clearly under the h1, not what I was after. I resorted to Thierry's excellent article on understanding the intricacies of z-index and then on to the css-discuss article on overlapping and z-index. Somewhere in between I hit the solution.

#content{z-index:1;position:relative;}

So there we are! Give some stacking order to the div wrapping your content columns, same again for the column in question (div id="secContent">) and then sandwich the photo between the two with z-index: -1.

Take a look at the example page and stripped-down CSS.

This entry was posted on Thursday, January 29th, 2009 at 12:06 pm and is filed under CSS. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

Categories

Connect

  • RSS
  • Linked In
  • Twitter
  • Flickr
  • Delicious

Delicious links