Bali Web Design Studio is a small enthusiast web design studio based in Bali, Jakarta, Indonesia.

Centering layout using CSS positioning & negative margin

Most developers using auto margin technique to create horizontally center CSS layout, by using this technique we simply specify the width of the content container and add CSS auto margin, and set the CSS text alignment of the parent element to center, but sometimes this technique does not come in handy.

<body>
	<div id="wrapper">
		Text Content
	</div>
<body>
body
	{
		text-align:center;
	}
#wrapper
	{
		width:780px;
		margin:0 auto;
	}

Today i was working on a design layout which need spesific centering CSS where i need to centering a layout but 100px more to the left, after googling around finally i solve this using CSS positioning and negative margin, and i thing this is easier than using auto margin

<body>
	<div id="wrapper">
		Text Content
	</div>
<body>
#wrapper
	{
		width:780px;
		position:relative;
		left:50%;
		margin-left:-390px /* half width */
	}

by setting the CSS left to 50% we put the wrapper left edge to the center of the screen and then the negative margin will move it half width to the left centering itself to the screen.

Using this technique we have advantages:

  • Control the CSS only in 1 declaration, while using auto margin we need to specify the center alignment on the parent declaration
  • More control on “how center” it is by adjust the negative margin value

In my case I simply reduce 100px more to the left margin

#wrapper
	{
		width:780px;
		position:relative;
		left:50%;
		margin-left:-490px /* 100px more to the left */
	}

5 Responses.

  1. Yong Luescher May 28, 2010

    For what it’s worth I’m glad that I took the full CSS approach for my intranet, and I believe that even with the amount of time spent adjusting and hacking it has already resulted in time savings and much improved consistency across pages.

  2. Kedar May 3, 2009

    Its only center to left side of browser not vertical align center

    This code is align any div to the center of the page correctly

    body
    { background:#333;
    margin:0;
    padding:0;
    text-align:center;
    }

    #wraper
    {margin:auto;
    width:780px;
    height:480px;
    position:absolute;
    left:50%;
    top:50%;
    margin-left:-390px; /* half width */
    margin-top:-240px; /* half width */
    background:#999;

    }

  3. chaosdreamer April 7, 2009

    good article but how about if we resize the browser or low resolution?thanks…

  4. michal January 26, 2009

    nice one komang

  5. ames January 25, 2009

    thank you! :) i loved your tutorial

Leave a Reply

bali web design studio Freelance Web Developer Works Bali Web Design Portfolio Get Web Design Quotation RSS Feeds