Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 7 ■ POSITIONING MODELS

Absolute


Problem You want to remove an element from the normal flow and move it into its own
layer. You also want to position it relative to the inner border of its closest
positioned ancestor, or you want it to be positioned at the same position it would
have had in the normal flow. You don’t want its position to have any effect on the
position of other elements.


Solution You can use position:absolute to render any element as an absolute box. You
can use width and height to size it. Percentages refer to its closest positioned
ancestor rather than its parent. You can assign a value, such as 0 , to left, right,
top, and bottom to align it to the sides of its closest position ancestor. Or you can
assign auto to left, right, top, and bottom to render it at the same position it
would have had in the normal flow. You can use margin-left, margin-right,
margin-top, and margin-bottom to offset its sides from the sides of its closest
positioned ancestor. You can use z-index to control the stacking order of the
element. Elements with a larger z-index are rendered in a layer closer to the user.
You can assign position:relative, position:absolute, or position:fixed to
an ancestor element to make it positioned. If you don’t have any positioned
ancestors, a browser uses as the closest positioned ancestor.


Patterns SELECTOR { position:absolute; 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; }
plus
ANCESTOR-SELECTOR { position:relative; }
or ANCESTOR-SELECTOR { position:absolute; }
or ANCESTOR-SELECTOR { position:fixed; }


Location You can absolutely position any type of element.


Limitations Internet Explorer 6 shrinkwraps stretched absolute elements. Internet Explorer 7
and earlier versions can’t center absolute elements.


Advantages Absolute elements give you precise control over their placement in relation to
their closest positioned ancestor. Absolute elements can be sized, shrinkwrapped,
and stretched. An absolute element is rendered in a layer above the normal flow
as an absolute box, which is much like a block box. Unlike floats, absolutes don’t
flow. Their position is unaffected by and doesn’t affect the position of other
elements and content. This may cause them to overlap or be overlapped. If all
children are positioned absolutely, the parent collapses to a height of zero (unless
you set the height to a value) because its children have been removed from the
normal flow.


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


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

Free download pdf