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.

1 Comments:

Wow!! That is fabulous! Fantastic! Great! Superb! Really professionally done. I wish you all the best and hope you can quietly walk away from the corporate world and enjoy your life as an artist! I can't think of a better way to spend a life.