Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 7 ■ POSITIONING MODELS

Closest Positioned Ancestor


Problem You want to position an element so you can position other elements in relation to
it. Such an element is the closest positioned ancestor to its descendants.


Solution You can position an element by assigning position:relative,
position:absolute, or position:fixed to it. Positioned elements are positioned
relative to their closest positioned ancestor. This allows you to remove elements
from the normal flow and position them far away from their original position in
the flow. Notice in the example how the absolute span (Absolute #2) is removed
from its non-positioned parent and aligned to the bottom right of its positioned
grandparent, which is its closest positioned ancestor.
When a positioned element has no positioned ancestor, is the positioned
ancestor. In other words, is positioned by default. Notice in the example
how the absolute division (Absolute #1) is removed from its non-positioned
parent and aligned to the bottom right of .
The main purpose for aligning positioned elements to their closest positioned
ancestors is to create self-contained layouts. You can reposition a self-contained
layout, and all its descendants will move along with it—both positioned and non-
positioned. Notice in the example how the absolute elements are positioned
relative to their closest positioned ancestors, as these ancestors are moved to the
bottom right of their closest positioned ancestors.


Pattern SELECTOR { position:relative; }
or
SELECTOR { position:absolute; }
or
SELECTOR { position:fixed; }


Location This pattern applies to all elements.


Limitations A closest positioned ancestor has to be an actual ancestor. CSS doesn’t provide a
way to position elements relative to any element in a document. That would be a
very welcome feature, but as it is, you must choose an ancestor to be the
reference for positioned elements.


Advantages There is no limit on how deep you can nest self-contained positioned layouts.
This is a very powerful feature for creating reusable layouts.


Disadvantages Positioning is very powerful, but its biggest weakness is that it ultimately requires
elements to be sized, and sized layouts don’t scale well on devices with displays
or fonts that are smaller or larger than designed for.


Tip position:relative is a great way to create a positioned ancestor because it
doesn’t remove it from the normal flow. This allows you to create layouts that
combine normal flow and absolute position.


Related to Positioned, Stacking Context, Atomic, Absolute, Fixed, Relative, Relative Float

Free download pdf