z-index

z-index is a CSS property that determines the stacking order of elements within a container. Elements with higher z-index values appear on top of elements with lower z-index values. z-index only affects elements that are positioned relative to each other (using position: relative, absolute, fixed, or sticky).

Basic Usage

  • Set the z-index property:
.element {
    z-index: 1;
}
  • Create a stacking order:
.element1 {
    z-index: 2;
}
.element2 {
    z-index: 1;
}

In this example, .element1 will appear on top of .element2.

Key Points

  • z-index values can be positive, negative, or zero.
  • Elements with a z-index of 0 or auto are stacked behind elements with positive z-index values.
  • Elements with negative z-index values are stacked behind all other elements.
  • z-index is inherited from parent elements.
  • z-index only affects elements within the same stacking context.

Best Practices

  • Use z-index sparingly to avoid complex stacking orders that can be difficult to maintain.
  • Consider using other CSS properties like opacity or visibility to control element visibility instead of relying solely on z-index.
  • If you need to create complex stacking orders, use a CSS framework like Bootstrap or Foundation that provides helper classes for managing z-index.

Additional Considerations

  • z-index can be affected by other CSS properties like transform and filter.
  • z-index can be used with position: sticky to create elements that stick to the viewport as you scroll.

Example with position: sticky

.sticky-element {
    position: sticky;
    top: 0;
    z-index: 1000;
}