Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 9 ■ POSITIONING: ADVANCED

Center Aligned


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


Solution To center-align content, assign text-align:center to its containing block.


To create a center-aligned sized element, you can use margin-left:auto; and
margin-right:auto; and set width:+VALUE to size it. For absolute elements, you can
also use right:0 and left:0 to align the element to the left and right sides.
To create a center-aligned stretched element, set margin-left and margin-right to
the same value. A larger value shrinks the element, and a smaller value grows it. For
absolute stretched elements, you can also use left:0 and right:0.

Patterns Center-aligned sized static block


BLOCK-SELECTOR { position:static; text-align:center;
width:+VALUE; margin-left:auto;
margin-right:auto; }


Center-aligned stretched static block


BLOCK-SELECTOR { position:static; text-align:center;
width:auto; margin-left:+VALUE;
margin-right:+VALUE; }


Center-aligned sized absolute element


SELECTOR { position:absolute; text-align:center;
width:+VALUE; left:0; margin-left:auto;
right:0; margin-right:auto; }


Center-aligned stretched absolute element


SELECTOR { position:absolute; text-align:center;
width:auto; left:0; margin-left:+VALUE;
right:0; margin-right:+VALUE; }


Location This pattern applies to all elements.


Limitations A horizontally shrinkwrapped element can’t be center aligned.
Internet Explorer 6 can’t center absolute elements; version 7 can center stretched
absolute elements but still can’t center sized absolute elements. Versions 8 and forward
do center sized absolute elements.


Tips A center-aligned sized pattern keeps the width constant and grows the margins
dynamically. A center-aligned stretched pattern grows the width dynamically and keeps
the margins constant. You can use percentages for widths and margins. A percentage
sizes the width or margin proportional to the width of the containing block.


Related to Left Aligned, Right Aligned, Center Offset; Static, Absolute (Chapter 7); Sized,
Shrinkwrapped, Stretched (Chapter 5); Aligned design patterns in Chapter 8

Free download pdf