tags:

views:

1030

answers:

2

How to horizonatally center a floating element of a variable width?

Edit: I already have this working using a containing div for the floating element and specifying a width for the container (then use margin: 0 auto; for the container). I just wanted to know whether it can be done without using a containing element or at least without having to specify a width for the containing element.

+1  A: 

Say you have a DIV you want centred horizontally:

 <div id="foo">Lorem ipsum</div>

In the CSS you'd style it with this:

#foo
{
  margin:0 auto; 
  width:30%;
}

Which states that you have a top and bottom margin of zero pixels, and on either left or right, automatically work out how much is needed to be even.

Doesn't really matter what you put in for the width, as long as it's there and isn't 100%. Otherwise you wouldn't be setting the centre on anything.

But if you float it, left or right, then the bets are off since that pulls it out of the normal flow of elements on the page and the auto margin setting won't work.

random
The only issue here is that you have to explicitly set the width; `width: auto;` doesn't work (AFAIK).
You
Correct, you do have to set something as the width. But the question was asking about variable width, hopefully that's not another word for auto and instead some fluctuating value or relative amount, like em's or %
random
Thanks for your answer, actually I don't have a problem with centering elements, what I'm trying to do is center a "floating element". I know this is not possible in CSS but was hoping somebody might have a hack that can work for this, I even tried to use a table but that didn't work too. Unfortunately in my scenario there's no way to make the element not floating, I need this for specific reasons.
Waleed Eissa
This solution helped me out on a project. Thanks.
Julian
+4  A: 

Assuming the element which is floated and will be centered is a div with an id="content" ...

<body>
<div id="wrap">
   <div id="content">
   This will be centered
   </div>
</div>
</body>

And apply the following CSS

#wrap
{
float: left;
position: relative;
left: 50%;
}

#content
{
float: left;
position: relative;
left: -50%;
}

Here is a good reference regarding that http://dev.opera.com/articles/view/35-floats-and-clearing/#centeringfloats

Leyu
Thanks, I'll have a look on this
Waleed Eissa