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

Asked 19-Jul-2021
Viewed 300 times

1

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


1 Answer


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?



Loading...
Ads