Cool HTML5 CSS Absolute Center Trick

I had been trying to figure out how to center elements vertically on a page using only CSS properties. Safari 3 finally offered a solution.


Posted in Blog || Posted on 2010-02-05 01:32:55

For the longest time, I've been trying to figure out just how exactly to center elements on a page using only CSS properties, and without having to use an HTML 4.01 transitional DTD and telling a table to be 100% wide and 100% tall, aligning it's contents to center, then valigning them to middle. I think I've finally found a way to do it.

Tonight, I stumbled across a really nifty little trick that Safari uses to center lone multimedia elements on pages. Safari does this when you visit links to MP3s or other Quicktime readable multimedia across the web, and the destination ends up being a browser window rather than a forced download. I discovered this when I right clicked on the background of one such page and selected the "Inspect Element" contextual menu item.

Screenshot of one of Safari's debug features showing off a really cool CSS trick

If you use Safari and don't have the "Inspect Element" contextual menu option available when you right click inside a page, you probably need to go to the "Advanced" tab in your Safari preferences and click the "Show Develop menu in menu bar" checkbox. FireFox users can get a similar functionality by installing FireBug, which is, for the record, totally the sweetest Javascript debugger around. That I have used. To date.

Anyway, here's a basically what's happening above:

<style> .center{ margin: auto; position: absolute; top: 0px; bottom: 0px; left: 0px; right: 0px; } </style> <img src="/some_image.png" class="center">

You can view a quick demo of this sweet trick in action on a quick little page I wrote up to test this, and download a copy of the source for the trick and play with it yourself.

Please keep in mind that this trick only works in the good browsers, and not in the bad browsers. Screenshots were provided by Adobe BrowserLab.

Remember kids, the sooner we can get all of our families and friends using one of "The GOOD browsers", the sooner IE will loose its market share, and the sooner we can to stop catering to Microsoft's inadequacies.

blog, html5, css, explorer sucks, webdesign

Space Bugs have invaded this page! Will you defend this Sector?