z-index - A Smarter Way To Learn HTML & CSS (2015)

A Smarter Way To Learn HTML & CSS(2015)

85
z-index

In the last chapter you learned that when you override the normal flow of a webpage by using fixed, absolute, or relative positioning, elements may overlap each other. Occasionally, you may want this to happen. For example, you might want to overlay a heading on top of an image.

You want the heading to be on top of the image, not the other way around. How do you tell the browser to put the heading on top? By specifying a z-index for the heading.

The higher the z-index, the higher it goes in the stack. An element with a z-index of 10 will sit on top of an element with a z-index of 9.

The default z-index of elements is 0. So if you give your heading a z-index of 1, it’ll be placed on top of the image, which, assuming you haven’t assigned it a z-index, has a z-index of 0.

h2#header {
z-index: 1;
}

If you give it a z-index of -1, it’ll be one layer below the default.

1. In your CSS file, code a div id.

2. Fix its position at the bottom-left.

3. Give it a z-index of -1.

4. In your HTML file, code the id. Place an image inside it: http://www.asmarterwaytolearn.com/monarch.jpg.

5. Save the files. Display the page. Scroll and see what happens.

Sample CSS code is at:
http://asmarterwaytolearn.com/htmlcss/practice-85-1.html.

Sample HTML code is at:
http://asmarterwaytolearn.com/htmlcss/practice-85-2.html.

Find the interactive coding exercises for this chapter at:
http://www.ASmarterWayToLearn.com/htmlcss/85.html