Centering with CSS

Centering things with css

About this article: Posted in: Learned along the way
By: Blockcoder ( Admin ) / 13.10.2011
Stats: one response / Views: 1,042
Tags: ,


  • you need a external css file, or write styles in the html ( but I don’t recommend this.. )
  • a browser of course for testing, I test with Firefox
  • a <div class=”container”></div> tag



<div class="container">your site content</div>

…and the css:

.container { margin: 0 auto; 
             width: 980px; 
             position: relative;  

Why this works?

You must add the width property, because you won’t see any change if you don’t define div’s width. Now with the position property being relative will make the container-div wrap around its inner content. When you write some text in the container div OR add maybe new div with property height: 100px, it will make the container also grow 100px tall.

How to center things with css

There’s one point I need to tell you anymore: you don’t really need to define all the margins to auto, only the margin-left and margin-right to get the div centered. I just think its faster way to center things just writing margin: auto auto; :) This “margin-left: auto;” and “margin-right: auto;” centering style with css is working because web browsers are required to give equal width for the container div.


In the end, just remember to define:

   margin: auto auto;
   position: relative; 

and your div’s width property to get things right! You can of course look any site’s css file and find there how it is centered — also Blockcoders’s!

Tip: shorten you css markup!

In case you didn’t know: you can shorten your css markup by writing only the two first, or only the first attribute of for example this case “margin”. Or like I used to write: all of them — it’s b-bad.

If you want, you can write markup like:

//first  -- all
margin: 10px 10px 10px 10px;

//second -- two first
margin: 10px 15px;

//third -- the first
margin: 10px;

  • First: top, right, bottom, left are separately marked 10px.
  • Second: top and bottom margins are marked 10px, left and right margin are 15px margin.
  • Third: all at once are marked 10px.

This method will speed up things when you get used to it. :)

There are 1 responses on this post

monday stocks to watch Thanks for that awesome posting. It saved MUCH time :-)

Leave a Reply

Your email address will not be published. Required fields are marked *


9,907 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>