• google plus

How to Use the CSS Z-index Property

The z-index property specifies the stack level of an element on the page compared to other elements in its same flow. Learn how to use the z-index property in the following steps.

  1. Set the z-index property for a selector.

    The z-index property takes a number as a value. The higher an element's z-index value, the closer to the user it appears.

  2. 
    .logo {
    	position:absolute;
    	top: 70px;
    	left: 50px;
    	z-index: 20;
    }
    	
  3. To see how the z-index property works, position another element so that it overlaps the first element and give it a different z-index value.
  4. 
    .logo {
    	position:absolute;
    	top: 70px;
    	left: 50px;
    	z-index: 20;
    }
    .logo2 {
    	position:absolute;
    	top: 75px;
    	left: 55px;
    	z-index: 10;
    }
    	
  5. The following example demonstrates the z-index property:
    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="UTF-8">
    <style type="text/css">
    .logo {
    	position:absolute;
    	font-family:Century;
    	font-size:2em;
    	font-weight:bold;
    	z-index:20;
    }
    #logo1 {
    	left:50px;
    	top:50px;
    	color:#00f;
    }
    #logo2 {
    	left:52px;
    	top:52px;
    	color:#f00;
    	z-index:10;
    }
    .box {
    	position:absolute;
    	height:100px;
    	width:100px;
    	border:15px solid #000;
    }
    #box1 {
    	left:150px;
    	top:150px;
    	border-color:#f00;
    	z-index:40;
    }
    #box2 {
    	left:185px;
    	top:185px;
    	border-color:#00f;
    	z-index:30;
    }
    #box3 {
    	left:185px;
    	top:150px;
    	border-color:#060;
    	z-index:20;
    }
    #box4 {
    	left:150px;
    	top:185px;
    	border-color:#f60;
    	z-index:10;
    }
    </style>
    <title>CSS Z-Index</title>
    </head>
    <body>
    	<h1>CSS Z-Index</h1>
    	<div id="logo1" class="logo">Webucator</div>
    	<div id="logo2" class="logo">Webucator</div>
    	<div id="box1" class="box"></div>
    	<div id="box2" class="box"></div>
    	<div id="box3" class="box"></div>
    	<div id="box4" class="box"></div>
    </body>
    </html>
    This code renders the following:
    z-index demo
Author: Chris Minnick
Chris is a prolific author and trainer, and the CEO of WatzThis?. His published books include Writing Computer Code, JavaScript for Kids, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW eCommerce Certification Bible, and New Riders' XHTML.
About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.