Wednesday, December 26, 2007

CSS: Vertical and Horizontal Centering with Cascading Style Sheets

For some time I had been looking for a simple and elegant solution to center a fixed sized block both vertically and horizontally ona web page using CSS. I had been using tables to do it, but anyone that has used tables for any length of time can attest to how complex the code can get and how hard it can be then to read and maintain.

I searched and found some proposed hacks to the problem. But none do it with a fixed sized object on a variable sized viewport (browser / screen size). Following my logic, I looked at it with the idea that I would need to set an anchor point then use relative positioning. So what I did was place a "block" that I knew I could place precisely and work from there. Looking at the CSS code, you will see that I place an object in the center of the page vertically and at 0 pixels in height. I then place the block which will house my content relative to that. Since the height is set at 400px for the content, I simply place it relatively -200px from the top of the #reference block.

I arbitrarily set the width of the #content block to 80% just to show the horizontal centering but on the page I made this solution for, I use a 100% width.

Here is the css code, small, simple, elegant, and effective across browsers (FireFox, IE7, Opera 9.2x, and Safari 3).

#reference {
display: block;
position: absolute;
top: 50%;
width: 100%;
height: 0px;
}

#content {
position: relative;
top: -200px;
left: 10%;
width: 80%;
height: 400px;
background-color:red;
}

Below is the HTML that puts it to use.


<html>

<head>


<title>Centering Test</title>


<link rel="stylesheet" type="text/css" href="test3.css" />

</head>


<body>


<div id="reference">

<div id="content">
Here is the big red centered box
</div> <!-- close for content -->

</div> <!-- close for referrence -->

</body>
</html>

Here is my site that puts this to use... Die Strafbar Photography