Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 8 ■ POSITIONING: INDENTED, OFFSET, AND ALIGNED

Aligned-center Absolute


Problem You want to align an absolutely positioned element to the horizontal and/or
vertical center of its closest positioned ancestor.


Solution Apply styles to your chosen class or ID as follows:^


To horizontally center:

Use width:+VALUE to specify the element’s width.
Use left:0 and right:0 to align the element to the left and right sides.
Use margin-left:auto and margin-right:auto to center the element.

To vertically center:
Use height:+VALUE to specify the element’s height.
Use top:0 and bottom:0 to align the element to the top and bottom.
Use margin-top:auto and margin-bottom:auto to center the element.

Patterns Vertically Aligned-center Absolute Element
SELECTOR { position:absolute; left:0; right:0;
margin-left:auto; margin-right:auto; }


Horizontally Aligned-center Absolute Element
SELECTOR { position:absolute; left:0; right:0;
margin-left:auto; margin-right:auto; }

Location This pattern applies to all elements.


Limitations This pattern doesn’t work in Internet Explorer 7 (and earlier versions) because it
doesn’t support aligning to the left and right sides at the same time, and it doesn’t
support aligning to the top and bottom sides at the same time.


Explanation This is an extension of the Aligned and Offset Absolute design pattern. It aligns an
element to the sides of its closest positioned ancestor and then uses automatic
margins to center it. The element must be sized for automatic margins to work.


Related to Indented; Positioned, Closest Positioned Ancestor, Absolute, Fixed (Chapter 7);
Center Aligned, Center Offset, Middle Aligned, Middle Offset (Chapter 9)

Free download pdf