There are a ton of posts about this topic, so I'm just writing this up in hopes I can remember it for this time. How can you center a div on a page? I'm working on a site that where the design requirements were fixed width. These days with mobile devices, I'm a much bigger fan fluid layouts, but that isn't this project.

So, my application needs to be some width, say 500 pixels, and centered within the screen. This is how I'm gonna do it. First, start with an HTML Page:

view plain print about
2 <head>
3 </head>
4 <body>
5 <div class="centereddiv">
6 <h1>Hello You!</h1>
7 </div>
8 </body>

There is an HTML body, with a div inside it, and some more content inside it. First, I'm going to add some CSS for the HTML and Body tags::

view plain print about
1html, body {
2 height: 100vh;
3 width: 100vw;
4 background-color: grey;
5 text-align: center;

This sets the HTML and body tags to the height and width of the viewport area using the vh and vw units. I also gave a grey background and told it to center its contents with text-align: center.

Now add some CSS for the centereddiv:

view plain print about
1.centereddiv {
2 width: 500px;
3 height: 100vh;
4 background-color: white;
5 display: inline-block;
6 text-align: left;

A width is specified. I used a pixel width, but this should work fine with a percentage width if you wish. The key part is the display being set to inline-block. This is the piece that tells this div to display in-line basd on the rules of the parent, and the parent uses text-align to center children. That is the magic.

I gave this a height of 100vh, and used text-align to left align the body, but neither matters for the purposes of this sample.

Try it out

It works pretty well.