
Z Index And Stacking Context in TailwindCSS
? Z-Index and Stacking Context in Tailwind CSS
The z-index controls the stacking order of elements that overlap, determining which element appears on top.
What is Z-Index?
The
z-index
property sets the stack order of positioned elements (position
other than static).Elements with higher
z-index
appear in front of elements with lowerz-index
.Only works on elements with a
position
ofrelative
,absolute
,fixed
, orsticky
.
Tailwind Z-Index Utilities
Tailwind provides a set of predefined z-index values:
Class | CSS Equivalent | Description |
---|---|---|
z-0 | z-index: 0; | Base level |
z-10 | z-index: 10; | Higher stack |
z-20 | z-index: 20; | Even higher |
z-30 | z-index: 30; | ... |
z-40 | z-index: 40; | ... |
z-50 | z-index: 50; | Topmost predefined |
z-auto | z-index: auto; | Default (inherits stacking) |
Usage Example
<div class="relative z-10 bg-blue-400 p-4"> I have z-index 10</div><div class="relative z-20 bg-red-400 p-4 -mt-8"> I have z-index 20 and will appear on top</div>
Stacking Context
A stacking context is created by certain CSS properties like
position
withz-index
,opacity < 1
,transform
,filter
,flex
containers, etc.Elements inside a stacking context are stacked relative to each other, but the entire context stacks relative to other contexts.
Understanding stacking contexts helps avoid unexpected layering issues.
Custom Z-Index Values
You can extend the z-index scale in tailwind.config.js
:
module.exports = { theme: { extend: { zIndex: { '60': '60', '70': '70', '80': '80', '90': '90', '100': '100', } } }}
Pro Tips
Always use positioned elements (
relative
,absolute
, etc.) when setting z-index.Use
z-auto
to reset to default stacking.Avoid very high z-index numbers unless necessary to keep layering manageable.
Would you like me to show you an example with a modal popup using z-index?