How to make a Horizontally Centered Box with XHTML/CSS
Guide Overview
The purpose of this guide is to show how a horizontally centered box can be achieved utilizing XHTML and CSS. The following example uses no tables and validates according to W3C standards. As is, this model is compatible with all modern browsers.
Instructions
- Open up Notepad or your preferred text editor.
- Copy and Paste the following code into your text editor of choice.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Horizontally Centered Fluid Box Model</title> <style type="text/css"> <!-- body { margin: 100px 0px; padding: 0px; /* Set margin and padding for cross browser consistency. */ text-align: center; /* Needed for IE5/Win */ } #content { width: 75%; margin: 0px auto; /* Right and left margin set to "auto", to center the box horizontally */ text-align: left; /* Needed to counteract IE5/Win alignment problem */ padding: 15px; border: 1px solid #000; background-color: #eee; } --> </style> </head> <body> <div id="content"> <h1>Horizontally centered fluid box model</h1> <p>Works in all modern browsers, and is also handy for nesting divs that need to fluctuate when resized. Resize the browser window to see it in action.</p> </div> </body> </html>
- Click File ---> Save as...
In Notepad, change the Save as type to All Files. Give your file a name with the extension .html and save it to the directory of your choice.
- Now, open the new .html file in your browser to see how it looks.
body {
margin: 100px 0px;
padding: 0px; /* Set margin and padding for cross browser consistency. */
text-align: center; /* Needed for IE5/Win */
}
#content {
width: 75%;
margin: 0px auto; /* Right and left margin set to "auto", to center the box horizontally */
text-align: left; /* Needed to counteract IE5/Win alignment problem */
padding: 15px;
border: 1px solid #000;
background-color: #eee;
}
- For this to work properly, a margin and padding value must be entered in the body CSS element. This example has a value of 100px for top and bottom margin, and 0px for left and right margin, and a value of 0px of padding. Both can be set to your needs..
- For this model to work with Internet Explorer 5 for Windows, the value of text-align: centered must be entered in the body CSS element. To get the content of the box aligned back to the left, the value of text-align: left should be added to the #content CSS element.
- In the #content CSS element, adjust the width: 75% shown in the example, to suit your needs.
- The following attributes shown in the example, are optional, and can be adjusted as desired. They were added for visual aid purposes.
padding: 15px;
border: 1px solid #000;
background-color: #eee;