Center a layout using CSS positioning and negative margin
22nd July 2012
Centering with Left property and negative margin
Setting the containers left property to 50% places the left edge of the container in the middle of the page. Then setting the margin-left property to half the containers width centers the container horizontally.
#outerContainer {Width:960px;left:50%;margin-left:-480px;}
/* Centered horizontally. */
/* Centered horizontally. */
The negative margin-left property can be increased to shift the container left the amount required, let's say 100 pixels left.
#outerContainer {Width:960px;left:50%;margin-left:-580px;}
/* Centered, then shifted left 100px. */
/* Centered, then shifted left 100px. */
The negative left margin will allowed the backdrop in the outer container to slide off-screen and the content inner frame to shift nearer to the left edge when the browser window is smaller than outer containers width.
Here's the CSS.
Line
- <!--
- __outerContainer______________
- | |
- | _______________________ |
- | |innerContainer | |
- | | article | |
- | | header | |
- | | nav | |
- | | | |
- | | | |
- | | [content] | |
- | | | |
- | | | |
- | | footer | |
- | |_____________________| |
- | |
- |____________________________|
- -->
- <style type="text/css">
- #outerContainer {
- position:absolute;
- width:960px;
- height:750px;
- top:0;
- left:50%;
- margin-left:-580px;
- /* half width plus left shift required. */
- text-align:left;
- background:url(images/facade.jpg) no-repeat center top;
- z-index:0;}
- /* Positions the box center but with a 100px shift to the
- left, the negative margin allowing background image to
- slide offscreen while the innerContainer division within
- is still visible if browser window is smaller than box
- width.
- Height is set to ensure whole of background image is
- shown vertically if innerContainer division does not
- extend to that height.*/
- #innerContainer {
- margin-top:150px;
- margin-left:385px;
- width:520px;}
- /* Box for content. Margins set box down and to the left
- of innerContainer division. */
- </style>