51

As a result of CSS trickery like negative margins, occasionally I have some HTML that is rendered below HTML content that occurs later in the HTML document. Even though the original elements should technically be below the later elements, I'd like to display the above the later elements.

Is it possible to make an HTML element appear above another element without having to specify an absolute position? It doesn't appear that z-index has any effect without an absolute position.

2 Answers 2

92

Yes: use position:relative; z-index:10.

z-index has no effect for position:static (the default).

Note that z-index is not a global layering system, but only differentiates ordering within each positioned parent. If you have:

<style type="text/css">
  div { position:relative }
  #a  { z-index:1  }
  #a1 { z-index:99 }
  #b  { z-index:2  }
</style>
...
<div id="a"><div id="a1">SUPER TALL</div></div>
<div id="b">I WIN</div>

...then #a1 will never render above b, because #b is layered above #a. You can see a demo of this at http://jsfiddle.net/DsTeK

6
  • 3
    the default is static? wow, I thought all these years it was relative
    – Jay
    Mar 12, 2012 at 21:23
  • @GoldenNewby You're welcome. I've added a demo of my second point to the answer.
    – Phrogz
    Mar 12, 2012 at 21:30
  • 1
    Yeah it worked in my code immediately. Just had to wait the minimum time before accepting. Mar 12, 2012 at 21:34
  • 2
    Your note (and demo) on not being global are extremely helpful
    – zimkies
    Jun 10, 2013 at 18:50
  • Thanks for mentioning that:- z-index is not a global layering system
    – geeksal
    Oct 5, 2016 at 8:35
14

I know Phrogz' answer has been accepted already, and a good answer it is, but just for the record: you don't always need z-index.

When you have position:relative on one element, it will also be displayed on top of all other elements that have no position (or position:static). Even if you don't have any z-indexes at all!

jsFiddle.

1
  • 4
    Just for completion, an element with position relative and a z-index of -1 will go beneath the static(default) elements Mar 13, 2012 at 7:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.