Centering a page using CSS

There’s a great trick here. Some pages on your site will have more content than others. When the user goes from one page to another and the vertical scrollbar appears or disappears then the centered page shifts. To fix this, I use CSS to always show scrollbars so that content centers consistently.

Also, because I’ve set the margins on the BODY tag to center the page I use a DIV inside the body to put some space around the content.

File “style.css”:

HTML {
min-height: 101%;
height: 101%;
background-color: grey;
}
BODY {
width: 800px;
margin-left: auto;
margin-right: auto;
background-color: white;
border: 1px solid black;
}
DIV#content {
padding: 12px;
}
File “example.html”:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" href="style.css" type="text/css" />
<title>CSS Page Centering Example</title>
</head>
<body>
<div id="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec accumsan libero vel massa fringilla porta. Vestibulum pellentesque porta justo, vel porttitor orci imperdiet ut. Nulla a eros a sem blandit accumsan ut ac elit. Praesent iaculis varius ante a pulvinar. Cras ipsum quam, pulvinar quis convallis ut, dictum id sapien. Phasellus suscipit ornare mi vitae vehicula. Ut non erat metus. Curabitur ac nunc justo, ut dictum massa. Maecenas quis felis ut metus placerat congue eget sed eros. Fusce venenatis massa quis risus dignissim non tincidunt nisi venenatis. Morbi a lorem tortor, at suscipit est. Donec est dolor, mattis eget elementum sed, sollicitudin ut diam. Praesent ac quam vitae libero vehicula tristique. Ut et dui nibh, et ultrices nibh. Aenean vehicula, erat tincidunt blandit mollis, lectus est rutrum felis, eu pharetra nulla turpis sit amet augue. Aliquam lobortis eros a velit dignissim et euismod lacus facilisis. Nunc ut nisi ut enim bibendum ultrices sed sed leo. Nullam vestibulum nibh velit.
</div>
</body>
</html>
Share this:
Share this page via Email Share this page via Stumble Upon Share this page via Digg this Share this page via Facebook Share this page via Twitter

Leave a Comment