What is the z-index
property in CSS and how is it used?
The z-index
property in CSS is used to specify the stack order of elements that overlap each other. It is particularly useful in layering elements on top of one another, such as when you have a modal dialog box appearing over a page.
Basic Usage
The z-index
property can only be applied to elements that have a position
property set to absolute
, relative
, fixed
, or sticky
. If z-index
is not specified, elements will stack according to document order.
Here's a simple example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .box1 { position: absolute; left: 50px; top: 50px; width: 100px; height: 100px; background-color: red; z-index: 1; } .box2 { position: absolute; left: 70px; top: 70px; width: 100px; height: 100px; background-color: blue; z-index: 2; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div> </body> </html>
In this example, .box2
will appear on top of .box1
because it has a higher z-index
value.
Considerations
- Default
z-index
: Ifz-index
is not set, the stacking order is determined by the order of elements in the HTML. - Negative
z-index
: You can use negative values to place an element behind its parent or sibling elements. - Same
z-index
: When elements have the samez-index
, they will stack in the order they appear in the HTML.
Common Pitfalls
- Only positioned elements (
position
set toabsolute
,relative
,fixed
, orsticky
) can have az-index
applied. z-index
values only have an effect within the stacking context of their parent.
Using z-index
effectively can help create visually appealing interfaces by layering content in a controlled manner.