Search code examples
htmlpositionpositioningcss-position

z-index won't take a relative position


I have a simple html page where i have a centered "stretchy" header. I want to have a centered logo on top of it. I'm using align="center" in the div tag to achieve centering. When I use z-index on the logo, it doesn't work unless I change position:relative to position:absolute, which breaks the centering that I have. I'm testing it in chrome 8.0.552.224 and FF 3.6.13

<!DOCTYPE html>
<html>
<head>
<title>Vassily's page!</title>
<style type="text/css">
* {margin:0; padding:0;}
table {border-collapse:collapse;}
body {background:white url("bg.png") top repeat-x fixed;}
#bar {opacity: .8;}
#bar_stretch {height:150px; width:55%;}
IMG#logo {position:relative; top:0px; z-index:10;}
</style>
</head>
<body>
<div align="center">
<img id="logo"  src="logo.png">
</div>
<div id="bar" align="center">
<img src="bar_left.png"><img src="bar_center.png" id="bar_stretch"><img       src="bar_right.png">
</div>
</body>
</html>

Solution

  • I've tested this in IE7, IE8, Firefox 3.6.13, Chrome dev (no IE6!):

    Live Demo
    (I had to use stupid images that actually exist or you can't view the demo properly in Firefox)

    HTML:

    <div id="logocontainer"><img id="logo" src="logo.png" /></div>
    <div id="bar">
        <img src="bar_left.png" /><img src="bar_center.png" id="bar_stretch" /><img src="bar_right.png" />
    </div>
    

    CSS:

    * {margin:0; padding:0}
    table {border-collapse:collapse}
    body {background:white url("bg.png") top repeat-x fixed}
    #bar {opacity: .8; text-align:center}
    #bar_stretch {height:150px; width:55%}
    
    #logocontainer {width:100%; position:absolute; text-align:center; z-index:1}
    #logo {margin-top:30px; width:123px; height:72px}
    

    This would be a whole lot cleaner if you could use CSS backgrounds instead of <img> in a few places.