Once you’ve started using CSS positioning to lay out your pages you’ll probably run across a problem with this technique. When you place your elements on the page, unless you’re very careful, they may overlap one another. This is fine if you want the last element to be the one on top. But what if you want the first or second element to be above the others? To do this, you need the z-index property of CSS.
If you’ve ever built graphics using a program like MS Paint or the graphics tools in Word and PowerPoint then, chances are, you’ve seen something like z-index in action. In these programs, you can highlight the object(s) that you’ve drawn, and choose an option "Send to back" or "Bring to front". This is essentially setting the z-index of those objects.
When you’re using CSS positioning to position elements on the page, you need to think in three dimensions. Each element on the page can be layered above or below any other element. The z-index determines where in the stack each element is. I like to think of the elements as pieces of paper, and the web page is a collage. Where I lay the paper is determined by positioning, and how much of it is covered by the other elements is the z-index.
The z-index is a number, either positive (e.g. 100) or negative (e.g. -100). The default z-index is 0. The element with the highest z-index is on top, followed by the next highest z-index and so on down to the lowest z-index. If two elements have the same z-index value (or it’s not defined) the browser will layer them in the order they appear in the HTML.
First, you need to have the position style set, usually to position:absolute;.
Then, you give each element you want layered a different z-index value. For example, if I have five different elements:
element 1 — z-index of -25element 2 — z-index of 82element 3 — z-index not setelement 4 — z-index of 10element 5 — z-index of -3
They will stack in the following order:
element 2element 4element 3element 5element 1
I recommend using vastly different z-index values to stack your elements. That way, if you add more elements to the page later, you have room to layer them in without having to adjust the z-index values of all the other elements. For example:
100 for my top-most element0 for my middle element-100 for my bottom element
You can also give two elements the same z-index value. If these elements are stacked, they will display in the order they are written in the HTML, with the last element on top.
I’ve created a simple page with several div elements positioned on top of one another. Take a look at the CSS to see the positioning and z-index values I used.
View the original article here
No comments:
Post a Comment