negative z-index disappears under background

11,551

Solution 1

When i see your picture, i think that absolute positioning is unnecessary. You could use fixed for the header, and let main content slides under it :
http://jsfiddle.net/jgYXr/

body {
    background:url(http://lorempixel.com/100/100/abstract/10);
}
nav {
    position:fixed;
    top:0;
    left:0;
    right:0;
    line-height:3em;
    background:tomato;
    box-shadow:0 0 1em 0.5em;
    text-align:right;
}
a {
    display:inline-block;
    margin:0 0.5em;
    padding:0 0.25em;
}
main {
    width:80%;
    background:rgba(255, 255, 255, 0.75);
    box-shadow:0 0 1em 0.3em;
    margin:2em auto;
    min-height:800px;
}
<nav> 
  <a href="#">Nav link</a>
  <a href="#">Nav link</a>
  <a href="#">Nav link</a>
</nav>
<main>
</main>

Search for position: fixed and how to size an element in absolute or fixed via coordinates. See as well to set height of 1 element that has only 1 line of text.

Solution 2

I came across this in my own code a few days back, and setting containing elements to position: relative solved the issue.

Share:
11,551
jeff
Author by

jeff

Updated on June 04, 2022

Comments

  • jeff
    jeff almost 2 years

    I'm trying to implement a div, that looks like a tall and narrow page, like a notebook paper.

    I have my content in <div id='centerframe'/> and I thought that a good solution was to use an absolute positioned div for the "paper".

    So I wrote the css rules as follows:

    div#center_background
    {
        z-index:-1;
        position:absolute;
        top:0;
        left:130px;
        width:900px;
        height:100%;
        background:rgba(255,255,255,0.9);
    }
    

    However, when I add a background image to body, it disappears under the background. I tried setting a positive z-index, than it renders on top of everything in the page, like centerframe, topbar etc. See the picture:

    A solution could be setting z-index for all the elements, which I really don't want to do, since I want to use position:absolute;'s as little as possible.

    So how can I define this kind of background div without changing other elements' positions and z-indices?

    I made a fiddle, but it runs as expected. The strange thing in my real code is, when I load the page, the center_background div appears on top of background of body for a glance, then it disappears. I don't change anything with JavaScript.