Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 7 ■ POSITIONING MODELS

145

Fixed


Problem You want to move an element into its own layer and fix its position to the viewport, or
you want it to be positioned at the same position it would have had in the normal
flow. You also don’t want the element to scroll when the viewport scrolls. This is
called a fixed-position element or a fixed element.


Solution You can use position:fixed to turn any element into a fixed-positioned element.
Fixed works identically to Absolute except that an element is positioned relative to
the viewport rather than its closest positioned ancestor, and the element doesn’t
scroll when the viewport scrolls. If you have positioned the fixed element at the same
position it would have had in the normal flow, it still doesn’t scroll when the viewport
scrolls.


Pattern SELECTOR { position:fixed; z-index:VALUE;
width:+VALUE; left:±VALUE; margin-left:±VALUE;
right:±VALUE; margin-right:±VALUE;
height:+VALUE; top:±VALUE; margin-top:±VALUE;
bottom:±VALUE; margin-bottom:VALUE; }


Location This pattern applies to all elements.


Limitations Internet Explorer 6 renders fixed-position elements as absolute. Internet Explorer 7
and above render fixed elements properly.


Advantages Fixed elements give you precise control over their placement in relation to the
viewport. They don’t scroll with the viewport. They’re well suited for holding
controls, such as menus, toolbars, buttons, and so on.


Disadvantages Layouts created using fixed positioning don’t scale well on devices with displays or
fonts that are much smaller than you designed for.


Example This example contains the same positioned elements as the Absolute design pattern
example. The only difference is the elements are fixed instead of absolute. Notice
how the browser window is scrolled down in the example, and the position of the
fixed elements remains the same. Notice how the fixed elements are positioned
relative to the viewport instead of their grandparent, which is the closest positioned
ancestor. Notice how the in-place absolute is initially positioned where it would have
been in the normal flow but remains fixed at that position and doesn’t scroll when
the viewport scrolls. If the in-place absolute is initially rendered offscreen, it won’t be
visible even when the viewport is scrolled.
Notice how the fixed elements in the example are layered exactly the same as the
absolute elements in the Absolute design pattern example. The in-place absolute is in
front of the sized absolute because it has a z-index of 1 and the sized absolute has a
z-index of auto. The stretched absolute is layered behind the positioned
grandparent because it has a z-index of -1 and the positioned grandparent has a z-
index of 1. Because the positioned grandparent has a transparent background, you
can see the stretched absolute element behind it.


Related to Absolute; Sized, Shrinkwrapped, Stretched (Chapter 5)


x
Free download pdf