Why are use z-index in CSS explain with example?

Asked 19-Jul-2021
Viewed 721 times

2 Answers


0

What is a Z Index?

Z Index (z-index) is a CSS property that defines the order of overlapping HTML elements. Elements with a higher index will be placed on top of elements with a lower index.

Note: Z index only works on positioned elements (position:absolute, position:relative, or position:fixed).

Possible Values

/* Default value if not specified */
z-index: auto;

/* Integer values */
z-index: 1;
z-index: 100;
z-index: 9999;
z-index: -1;

/* Global values */
z-index: inherit;
z-index: initial;
z-index: unset;

How to use the Z Index

In this example, you can see three boxes displayed on top of each other in different orders using z-index.

HTML

<div class='container'>
  <div class='box' id='blue'></div>
  <div class='box' id='red'></div>
  <div class='box' id='green'></div>
</div>

CSS

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#green {
  background-color: green;
}

 


1

The z-index property stores any element in the order of the stack. Whichever element has higher stack order is shown first and whichever has a lower stack is shown below the higher element.

 Note:  z-index only works on positioned elements (absolute, relative, fixed, or sticky) and flex items (elements that are direct children of display: flex elements).

Example 

<!DOCTYPE html>

<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title></title>
    <style>
        body {
            box-sizing: border-box;
            margin: 0px;
            padding: 0px;
        }
        div {
            border-radius:10px;
        }
        .center {
            display:flex;
            justify-content: center;
            width: 100%;
            align-items: center;
            height: 100vh;
            position:relative;
            text-align:center;
            font-weight:bold;
            font-size:25px;
        }
        #first {
            width: 80%;
            height: 80%;
            background-color: black;
            color: white;
            border: 1px solid black;
            z-index: 1;
            position:absolute;
        }
        #middle {
            z-index: 3;
            position:absolute;
            width: 60%;
            height: 60%;
            background-color: red;
            color: white;
            border: 1px solid red;
        }
        #last {
            z-index: 5;
            position:absolute;
            width: 40%;
            height: 40%;
            background-color: blue;
            color: white;
            border: 1px solid blue;
        }
    </style>
</head>
<body>
    <div class='center'>
        <div id='last'>Last div</div>
        <div id='middle'>middle div </div>
        <div id='first'>first div</div>
    </div>
</body>
</html>

    Why are use z-index in CSS explain with example?