Published: 2nd May 2017 | Words: 521 | Reading Time: 3 minutes


Building web page layers

The z-index is probably my favourite CSS property to work with. The z-index of a page element is its stacking order in the document. To simplify this down let’s say you have 10 div’s / blocks on your page, each the same size. Div’s are block level elements and each of them would struggle for their nearest space and push the next one below it leading to a line of div’s down the page. By placing a position like absolute on the div’s and setting z-indexes on them you can place them on top or below each other in whatever order you want. What you can consider the default document z-index is 0. Your actual page will be at this z-index, and you can develop your elements to sit above or below it, or you can technically set the default document z-index to a different value by using a container. There is a number of ways to position z-index elements, by using a margin etc. and by setting a relative position on the containing element.

Z-index stacking

The scope of what you can do is huge. By being able to stack elements in layers on top of each other you can create very complex layouts; pretty much anything you can imagine. You can use things like transparent PNG’s, animated gifs, CSS, and JavaScript to animate these different layers and create some pretty striking and unbelievable stuff. There is a limit on the z-index value but it is far beyond anything you would use no matter how complex the design. The limit is something like 2147483647. You may go a few thousand on your z-index, I prefer to work between the range of -10000 and 10000 with 10000 the top element in the stack and -10000 for the bottom element in the stack.

Positioning bugs

Absolute positioning can cause issues in some browsers and setting z-index properties on all your absolutely positioned elements can help stop these bugs. When you’re actually positioning your elements take care about things like menus and fixed elements. If you have a document with a complex stacking order make sure to test how fixed elements stack against page elements as the window scrolls.

CSS3 and the z-index

A lot of CSS3 effects are based on the z-index and stacking. You may find across the web complex and very beautiful buttons with animated hover effects, borders and shadows. A lot of these will be built using :before or :after pseudo elements and stacking using z-indexes. You can actually place div’s within div’s and animate the layers of the stack in different ways. You can also change the z-index on hover and other events and create some interesting effects. There is no end to actually what you can do and the only way to experience the power of the z-index is to experiment. Think of something crazy and complex that requires different layers and try to build it.