Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Z-Index without absolute position

Tags:

html

css

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.

like image 290
GoldenNewby Avatar asked Mar 12 '12 21:03

GoldenNewby


People also ask

Does Z Index work without position absolute?

An element with greater stack order is always in front of an element with a lower stack order. Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).

Does Z Index require position?

Note: Z index only works on positioned elements ( position:absolute , position:relative , or position:fixed ).

Is Z Index absolute or relative?

The z-index of elements inside of a stacking context are always relative to the parent's current order in its own stacking context. The <html> element is a stacking context itself and nothing can ever go behind it.

Why is Z Index not working CSS?

z-index only works on positioned elements (relative, absolute, fixed, sticky) so if you set a z-index on an element with a static position, it won't work.


2 Answers

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

like image 124
Phrogz Avatar answered Sep 27 '22 22:09

Phrogz


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.

like image 32
Mr Lister Avatar answered Sep 27 '22 22:09

Mr Lister