Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 9 ■ POSITIONING: ADVANCED

Middle Aligned


Problem You want to align an element and its content to the vertical middle of its closest
positioned ancestor.


Solution To create a middle-aligned inline element, assign line-height:+VALUE to the same
measurement or percentage assigned to the height of its parent. This pattern requires the
element’s parent to be sized.
To create a middle-aligned sized absolute element, set height to size it. You can use
top:0 and bottom:0 to align the element to the top and bottom. You can use margin-
top:auto and margin-bottom:auto to realign the element to the middle.
To create a middle-aligned stretched absolute element, set margin-top and margin-
bottom to the same value. A larger value shrinks the element, and a smaller value grows it.
A negative value expands the element beyond the height of its container. You can use
top:0 and bottom:0 to align the element to the top and bottom.
A static element can’t be middle aligned.
A shrinkwrapped element can’t be middle aligned.


Patterns Middle-aligned inline element


SELECTOR { line-height:+VALUE; }


Middle-aligned sized absolute element


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


Middle-aligned stretched absolute element


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


Location This pattern works only on absolute elements.


Limitations Internet Explorer 6 can’t middle-align absolute elements. Version 7 can middle-align
stretched absolute elements but not sized absolute elements. These problems are resolved
in versions 8 and 9.


Tip There is no text-align property to align content to the middle. Instead, you need to wrap
content in an inline element, absolutely position it, and align it to the middle. This
technique only works with elements that are inside stretched or sized absolute elements.


Example In the example, this pattern aligns the content in each division to the middle of its parent
division. The inline content is middle aligned. The elements are middle aligned.
The divisions are middle aligned.


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

Free download pdf