Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 9 ■ POSITIONING: ADVANCED

Top Aligned


Problem


You want to align an element and its content to the top of its parent or closest positioned
ancestor.

Solution


To create a top-aligned sized element, you can use height:+VALUE to size it. You can use
margin-top:0 to align it to the top. You can use margin-bottom:auto to prevent it from
aligning to the bottom. For an absolute element, you can also use top:0 to align the
element to the top and bottom:auto to prevent it from aligning to the bottom.
To create a top-aligned shrinkwrapped element, you can use height:auto,
bottom:auto, and margin-bottom:auto to shrinkwrap the height. You can use top:0 and
margin-top:0 to align it to the top.
To create a top-aligned stretched element, you can use height:auto, margin-top:0, and
margin-bottom:0 to stretch its height to the top and bottom of its container. For an
absolute element, you can also use top:0 and bottom:0 to stretch it to the top and bottom.

Patterns Top-aligned sized static block


BLOCK-SELECTOR { position:static; height:+VALUE;
margin-top:0; margin-bottom:auto; }


Top-aligned shrinkwrapped static block


BLOCK-SELECTOR { position:static; height:auto;
margin-top:0; margin-bottom:0; }


Top-aligned sized absolute element


SELECTOR { position:absolute; height:+VALUE;
margin-top:0; margin-bottom:auto;
top:0; bottom:auto; }


Top-aligned shrinkwrapped absolute element


SELECTOR { position:absolute; height:auto;
margin-top:0; margin-bottom:auto;
top:0; bottom:auto; }


Top-aligned stretched absolute element


SELECTOR { position:absolute; height:auto;
margin-top:0; margin-bottom:0;
top:0; bottom:0; }


Location This pattern applies to all elements.


Limitations


Stretched Absolute doesn’t work in Internet Explorer 6, but it does work in more recent
versions.

Tip


A browser renders blocks and content starting at the top of their containers and flows them
down. This automatically aligns the first item to the top of its container and the top of the
next item to the bottom of the previous item.

Related to
Top Offset, Bottom Aligned, Middle Aligned; Static, Absolute (Chapter 7); Sized,
Shrinkwrapped, Stretched (Chapter 5)

Free download pdf