Junior
What is z-index and how is it used in web development?
sobes.tech AI
Answer from AI
z-index is a CSS property that determines the stacking order of elements along the Z-axis. Elements with higher z-index values are displayed above those with lower values.
It is used to control the stacking depth of positioned elements (i.e., elements with a position property other than static): relative, absolute, fixed, sticky.
Key points of usage:
- Static positioned elements (
position: static;) do not participate in stacking contexts and ignorez-index. - The
z-indexvalue applies only to elements that create a new stacking context. Such a context is created, for example, when usingpositionwith values other thanstatic, or applying certain other CSS rules (e.g.,opacity< 1). - Within a stacking context, elements with higher
z-indexare placed above those with lowerz-index. - Nested stacking contexts are stacked as a whole within the parent context.
- Without an explicit
z-index, the stacking order is determined by the order of elements in the DOM.
Example of usage:
.box1 {
position: absolute;
top: 10px;
left: 10px;
width: 100px;
height: 100px;
background-color: red;
z-index: 2; /* Will be above .box2 */
}
.box2 {
position: absolute;
top: 30px;
left: 30px;
width: 100px;
height: 100px;
background-color: blue;
z-index: 1; /* Will be below .box1 */
}