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

0 votes
64 views
Ravi Vishwakarma asked 12 days ago in Web Application by Ravi Vishwakarma

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

1 Answer

1 votes
Ethan Karla answered 9 days ago by Ethan Karla
The z-index property specifies the stack order of an element.
An element with greater stack order is always in front of an element with a lower stack order.
 z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).
<!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:50px;
        }
        .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>