Placing absolute behind relative positioned element
Asked Answered
T

4

61

I have two elements in the same container, the first has position: absolute, the second position: relative. Is there a way to set the "z-index" of an absolute element so that its in the background? The relative positioned element should be on the top (z-layer) because it holds links...

Here is a JSFiddle: http://jsfiddle.net/8eLJz/

The absolute positioned element is on the top of the z-layer and I have no influence with the z-index-property. What can I do?

Twinned answered 3/3, 2014 at 15:55 Comment(0)
A
84

I'm not sure which one you want in front, but you just need to set position on both and set z-index on both. http://jsfiddle.net/8eLJz/2/

a {
    color: black;
}

nav#mainNav {
    position: relative;
}

nav#mainNav > img {
    position: absolute;
    width: 100px;
    left: 0;
    z-index: 5;
}

nav#mainNav > a > img {
    width: 100%;
}

nav#mainNav > nav {
    width: 100%;
    position: relative;
    z-index: 10;
}

nav#mainNav > nav > a {
    display: block;
    text-align: right;
    background-color: yellow;
}
Albumen answered 3/3, 2014 at 16:2 Comment(0)
M
26

You can put a negative z-index on the image, which will cause it to layer behind the other elements:

a {
  color: black;
}

nav#mainNav {
  position: relative;
}

nav#mainNav>img {
  position: absolute;
  width: 100px;
  left: 0;
  z-index: -1; /* <----------------------------------- HERE I AM! */
}

nav#mainNav>a>img {
  width: 100%;
}

nav#mainNav>nav {
  width: 100%;
}

nav#mainNav>nav>a {
  display: block;
  text-align: right;
  background-color: yellow;
}
<nav id="mainNav">
  <img src="http://www.colourbox.com/preview/7389458-682747-example-stamp.jpg" />
  <nav> <a href="/">Some Text</a>
    <a href="/">Some Text</a>
  </nav>
</nav>
Mess answered 3/3, 2014 at 16:2 Comment(0)
A
3

CSS has a z-index property so on your nav#mainNav > img selector just set z-index: -1;. Here is a working jsFiddle: http://jsfiddle.net/8eLJz/1/

Alcaide answered 3/3, 2014 at 16:2 Comment(0)
D
1

I think the order of items(position relative one and position absolute one) is important too.

a {
    color: black;
}

nav#mainNav {
    position: relative;
}

nav#mainNav > img {
    position: absolute;
    width: 100px;
    left: 0;
    z-index: -1;
}

nav#mainNav > nav {
    width: 100%;
}

nav#mainNav > nav > a {
    display: block;
}
<nav id="mainNav">
    <!-- this one first -->
    <img
        src="http://www.colourbox.com/preview/7389458-682747-example-stamp.jpg"
    />
    
    <!-- this one second -->
    <nav>
        <a href="/">Some Text</a>
        <a href="/">Some Text</a>
    </nav>
</nav>

It doesn't work for me if I change the order

Demantoid answered 18/8, 2022 at 7:50 Comment(1)
the order does not matter, your problem is you don't have position and z-index set on nav#mainNav > navAlbumen

© 2022 - 2024 — McMap. All rights reserved.