Check out our Angular Book Series.

How to center a div on a page using CSS?

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:


<html>
<head>
</head>
<body>
<div class="centereddiv">
<h1>Hello You!</h1>
</div>
</body>
</html>

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::


html, body {
height: 100vh;
width: 100vw;
background-color: grey;
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:


.centereddiv {
width: 500px;
height: 100vh;
background-color: white;
display: inline-block;
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.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.