CSS: z-index and layering order

Do you remember how layers work in Photoshop? An outer layer will be always over an inner layer, and when you try to select the underlying layer while you're still working on an upper layer, then nothing happens. The same thing happens in CSS with the z-index property and the layering order. We're talking about layers, and this is not a coincidence. In fact, it was Netscape that introduced the concept of layers that has been later developed by CSS through the positioning model. The layering order comes into play when two or more positioned elements overlap. In this case, the z-index property will tell browsers which element must be put on a higher layer.

This property accepts integer values, both positive and negative. If a positioned element has a z-index of 1 and another positioned element has a z-index of 2, then the latter will be put on a higher layer than the former. What does this mean? In a nutshell: the former will be covered by the latter, just as in Photoshop. So if you try to select some content of the former, you will probably see that the browser doesn't allow you to select anything (e.g. text). In other cases, instead, the content of the former will be completely or partially hidden. Let's do an example. Suppose that we have this HTML structure:

<div id="outer">
Test 1
  <div id="inner">Test 2</div>

  <div id="overlay"><p>Test 3</p></div>
</div>

with the following styles:

#outer {
	position: relative;
	width: 300px;
	height: 200px;
	background: silver;
	z-index: 0;
}

#inner {
	width: 150px;
	height: 100px;
	background: teal;
	position: absolute;
	top: 50%;
	left: 50%;
	margin: -50px 0 0 -75px;
	z-index: 2;
}

#overlay {
	width: 150px;
	height: 100px;
	border: 1px solid red;
	position: absolute;
	top: 50%;
	left: 50%;
	margin: -50px 0 0 -75px;
	z-index: 1;
	padding: 5px;
}

In this case, the inner element will cover the contents of the overlay element, because it has a greater z-index value. Note that this happens even when our element has a transparent background color, just as the overlay element. If you take a look at the test page below, you will see that the text Test 3 is not visible on the page.

Test

Live test

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.