The stacking order of the positioned elements can be controlled by setting the z-index property. The higher the z-index, the higher up the box appears in the stack.
The z-index property is used to control layering of positioned elements along an invisible z-axis, which can be thought as an line coming out of the computer screen. It can take values as
- auto – Sets the stack order equal to its parents.
- number – Sets the stack order of the element. Negative numbers are allowed
Its default value is ‘auto’ keyword and is used as
div { position: absolute; z-index: auto; width: 100px; height: 100px; }
Only elements with an integer value z-index create stacking contexts. The stacking order using an number value for the z-index property is shown in the example
<style>
div {position: absolute; border: solid;
width: 5em; height: 5em; background: silver;
text-align: right}
.a1 {top: 1em; left: 1em; z-index: 3}
.a2 {top: 2em; left: 3em; z-index: 2}
.a3 {top: 3em; left: 2em; z-index: 4}
.a4 {top: 4em; left: 4em; z-index: 1}
</ style >
No elements within a stacking context will appear above the z-index of the element that created the context. Management of z-index values should be done instead of a free-for-all over in which content appears on top.