float:center

July 12th, 2006 4 minutes reading time.


You wish…

So many work arounds to center divs, that I was almost getting to the point where I was about to start selling black t-shirts with the words

float:center

If you’re a web developer, web designer, and you have to deal with CSS, and CSS not working properly on IE (cause of it’s stupid box model conception and endless ilogic behaviour bugs) then I’m sure you have always wanted to be able to do something like “float:center”

I don’t really get why the people that made the CSS standards, didn’t include stupid float:center… there’s float:left, float:right… it’s only obvious. And worst of all, you know centering is one very important thing…

so we have to go around doing stuff like

margin:0 auto;

but that won’t really work on all occasions, you have to think of the size of the parent elements too, so that the auto margins will work correctly.

The other day a friend that’s a graphic designer even came up with his own trick of using percentages to add correct margins to center divs.

But look no more (at least until they decide to give us float:center), if you use Prototype, maybe you also use Scriptaculous…

Just add this to your effects.js file:


Effect.Center = function(element)
{
try
{
element = $(element);
}
catch(e)
{
return;
}

var my_width = 0;
var my_height = 0;

if ( typeof( window.innerWidth ) == 'number' )
{

my_width = window.innerWidth;
my_height = window.innerHeight;
}
else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
{

my_width = document.documentElement.clientWidth;
my_height = document.documentElement.clientHeight;
}
else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
{

my_width = document.body.clientWidth;
my_height = document.body.clientHeight;
}

element.style.position = 'absolute';
element.style.display = 'block';
element.style.zIndex = 99;

var scrollY = 0;

if ( document.documentElement && document.documentElement.scrollTop )
{
scrollY = document.documentElement.scrollTop;
}
else if ( document.body && document.body.scrollTop )
{
scrollY = document.body.scrollTop;
}
else if ( window.pageYOffset )
{
scrollY = window.pageYOffset;
}
else if ( window.scrollY )
{
scrollY = window.scrollY;
}

var elementDimensions = Element.getDimensions(element);

var setX = ( my_width - elementDimensions.width ) / 2;
var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;

setX = ( setX

This will center your div if you do something like this on Javascript to the div in question:


Effect.Center('idOfMyDiv')

Try it, it works.
You might want to hack the function in case you don't want this effect to center vertically.

Also, if you want to keep centering the div even on window resize or scroll, you'll have to add
callbacks to window.onresize and window.onscroll

And remember, Linux Rules.

Leave a Reply