margin: auto;

#main {
  width: 600px;
  margin: 0 auto; 
}
<div id="main">

Setting the width of a block-level element will prevent it from stretching out to the edges of its container to the left and right. Then, you can set the left and right margins to auto to horizontally center that element within its container. The element will take up the width you specify, then the remaining space will be split evenly between the two margins.

The only problem occurs when the browser window is narrower than the width of your element. The browser resolves this by creating a horizontal scrollbar on the page. Let's improve the situation...

</div>
  • Creative Commons License
  • Ads by Bocoup