How to Center Web Pages Using CSS

When you design your own web page, you may want to position it to remain in the center of the browser window even if it is minimized or stretched out. You can achieve this formatting by using Cascading Style Sheets (CSS) in your HyperText Markup Language (HTML) code. This will prevent a lot of extra markup that could prolong how long it takes for your page to load. By creating a couple of CSS styles, you can quickly center your own web page.

Things You'll Need

  • HTML text editor
Show More

Instructions

    • 1

      Launch your HTML text editor and begin a new page or open an existing one.

    • 2

      Locate the "<head></head>" portion at the top of the code, place your cursor in between the two elements and begin the CSS "body" style rule that controls your overall page. For example:
      <head>
      <style type="text/css">
      <!--
      body { }
      -->
      </style>
      </head>

    • 3

      Enter a value of zero for the "margin" and "padding" attributes so that your page appears correctly on browsers that have different display defaults. Enter "margin: 0;" and "padding: 0;" within the "body" tag as such:
      body { margin: 0; padding: 0; }

    • 4

      Choose a term for a new style rule that manages the location holding the content of your web page (for example, "container"). Enter this term, preceded by a period, underneath the "body" rule as follows:
      .container { }

    • 5

      Enter a "width" attribute in the tag from Step 4. This attribute determines how wide your page will be, using a measurement term such as pixels (for example, "780px"). Then, enter "margin: 0 auto;" to allow this setting to work in alliance with the "body" rule to center your page. For instance:
      .container { width: 780px; margin: 0 auto; }

    • 6

      Use your text editor's "Preview" function to view your centered web page.

    • 7

      Save your document.

Tips & Warnings

  • If you do not want a horizontal scroll bar to appear on your page, do not make your page width larger than 780 pixels (Step 5).

Related Searches:

References

Resources

Comments

You May Also Like

Related Ads

Featured