How to center body on a page?

206,679

Solution 1

Also apply text-align: center; on the html element like so:

html {
  text-align: center;
}

A better approach though is to have an inner container div, which will be centralized, and not the body.

Solution 2

    body
    {
        width:80%;
        margin-left:auto;
        margin-right:auto;
    }

This will work on most browsers, including IE.

Solution 3

You have to specify the width to the body for it to center on the page.

Or put all the content in the div and center it.

<body>
    <div>
    jhfgdfjh
    </div>
</body>​

div {
    margin: 0px auto;
    width:400px;
}

Solution 4

For those that do know the width, you could do something like

div {
     max-width: ???px; //px,%
     margin-left:auto;
     margin-right:auto;
}

I also agree about not setting text-align:center on the body because it can mess up the rest of your code and you might have to individually set text-align:left on a lot of things either then or in the future.

Share:
206,679
Ryan Peschel
Author by

Ryan Peschel

Updated on April 13, 2020

Comments

  • Ryan Peschel
    Ryan Peschel about 4 years

    I'm trying to center the body element on my HTML page.

    enter image description here

    Basically, in the CSS I set the body element to be display: inline-block; so that it is only as wide as its contents. That works fine. However, margin: 0px auto; doesn't center it on the page.

    Does anyone know how to fix this? I want the big blue square to be centered on the page, not floating to the left like it is now.

    Here's my CSS:

    body {
        display: inline-block;
        margin: 0px auto;
        text-align: center;
    }