Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

Controlling Stacking 303

11


One thing you might notice in the figure is that the bar covers some of the text at the bot-
tom of the page. Both fixed and absolute positioning remove the element from the normal
flow, so the browser does not take the fixed element into account when it creates the
scrollbar for the page’s vertical scrolling. When you use fixed elements, you may need
to strategically add whitespace to the page so that parts of the page are not permanently
covered by those elements. To make sure that the bottom of the final paragraph on the
page is not permanently covered by the bar I added to the bottom of the viewport, I added
this style:


p:last-of-type {
padding-bottom: 2em;
}


It adds some padding to the bottom of the last paragraph on the page, creating enough
space for all of the text to be displayed. There are other ways to add whitespace as well;
this is just the one I chose.


Controlling Stacking


CSS provides a way of taking control over how overlapping elements are presented.
The z-index property is used to manually specify a value for the stacking order associ-
ated with a selector. By default, elements that appear in the same layer of a document
are stacked in source order. In other words, an element that appears after another in the
HTML source for the page will generally be stacked above it. The easiest way to think
about it is to think of all of the elements on a page being numbered from first to last in
the source. Larger numbers are stacked above smaller numbers.


By manually assigning z-index values for elements, however, you can put elements in
specific stacking layers. If all elements appear in stacking layer 0 by default, any element
in stacking layer 1 (z-index: 1) will appear above all elements in layer 0. The catch
here is that z-index can be applied only to elements that are positioned. Elements in the
normal flow always appear below relatively or absolutely positioned elements. The stack-
ing layers below 0 are considered beneath the body element, so they don’t show up at all.


If you want to have an element in the normal flow but you want to
control its stacking layer, assign it the relative positioning scheme
and don’t specify a position. It will appear on the page normally,
but you will be able to apply a z-index to it.

TIP
Free download pdf