Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 9 ■ POSITIONING: ADVANCED

Center Offset


Problem You want to align an element and its content to the center of its parent or closest
positioned ancestor and then offset it from the center.


Solution To create a center-offset inline element, you can use margin-left:+VALUE to offset the
element to the right and margin-left:-VALUE to offset it to the left. Also assign text-
align:center to the containing block element.
To create a center-offset sized absolute element, you can use a positive value in left to
offset to the right and a negative value to offset to the left. You can also assign the following
to the element: margin-left:auto;, margin-right:auto;, and right:0;, and set
width:+VALUE to size the element.
To create a center-offset stretched element, set margin-left and margin-right to the
same value. A larger value shrinks the element, and a smaller value grows it. To offset it to
the left, subtract the desired offset from margin-left and add it to margin-right. To offset
it to the right, add the desired offset to margin-left and subtract it from margin-right.
For absolute stretched elements, you can also use left:0 and right:0.
A sized static block element can’t be center offset.
A shrinkwrapped absolute element can’t be center offset.


Patterns Center-offset inline element


INLINE-SELECTOR { margin-left:±VALUE; }
BLOCK-SELECTOR { text-align:center; }


Center-offset stretched static block


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


Center-offset sized absolute element


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


Center-offset 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 Same as Center Aligned.


Example Notice how each block is centered and then offset to the right by 80 pixels. Also notice how
the text in each block is centered and then offset to the left by 40 pixels.


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

Free download pdf