Width, Max-Width & Margin: Auto

Block-level elements always takes up the full width available, stretching out to the left and right as far as it can. Setting the width of a block-level element will prevent it from stretching out to the edges of its container. Then, you can set the margins to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins:

The CSS stylesheet:

div.ex1 {
   width: 500px;
   margin: auto;
   border: 3px solid #8AC007;
}
div.ex2 {
   max-width: 500px;
   margin: auto;
   border: 3px solid #8AC007;
}

Displayed by browser:

This div element has width: 500px;

This div element has max-width: 500px;

Note: A problem occurs when the browser window is smaller than the width of the element. The browser then adds a horizontal scrollbar to the page. Using max-width instead, improves the browser's handling of small windows. This is important when making a site usable on small devices. Drag the browser window to smaller than 500px wide, to see the difference between the two elements! (Incidentally, this does not work inside a table.)

Back button Table of Contents Next button