30

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;
}
Ryan Peschel
  • 9,095
  • 18
  • 57
  • 101

4 Answers4

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

This will work on most browsers, including IE.

Freakishly
  • 1,453
  • 3
  • 28
  • 56
30

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.

Madara's Ghost
  • 158,961
  • 49
  • 244
  • 292
  • 1
    This is exactly what was requested, why is it getting down voted? http://jsfiddle.net/gA9La/2/ – barro32 Jun 03 '12 at 18:22
  • I also had to set the body's display property for this to work: `body {display: inline-block;}` – Parris Varney Dec 09 '15 at 18:32
  • @ParrisVarney Yes, that is implied (Look at OP's CSS). – Madara's Ghost Dec 09 '15 at 19:11
  • I think Freakishly answer is far better than this one. No offense Madara but its answer should be the accepted one and not yours since your proposal is not the good way to center other items than texts. – AFract Apr 13 '16 at 13:01
  • @AFract The requirement was to keep the element as wide as the contents, Freakishly doesn't take that into account, at all. So while it's probably better practice to use his, it doesn't answer the question as it was asked at all. – Madara's Ghost Apr 13 '16 at 13:03
  • I see what you mean. Maybe I stick too much on first sentence "I'm trying to center the body element on my HTML page." :) – AFract Apr 13 '16 at 13:04
  • that also "centers" all text content of page, so not working well. – tanaydin Sep 09 '18 at 14:16
  • 1
    @tanaydin So you add `body { text-align: initial; }` and are good to go :) – Madara's Ghost Sep 10 '18 at 16:23
10

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;
}

McGarnagle
  • 96,448
  • 30
  • 213
  • 255
SRN
  • 2,144
  • 3
  • 19
  • 26
3

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.

DardanM
  • 85
  • 8