|
Posted by Ben C on 10/19/06 21:26
On 2006-10-19, Ben C <spamspam@spam.eggs> wrote:
> On 2006-10-18, X l e c t r i c <Xlectric@webtv.net> wrote:
>> I don't know why the absolute positioning is necessary.
>
> It was to get shrink-to-fit width on the <ul>. Your divs are nicely
> centered, but you had to set widths on them. If they were width: auto,
> they'd fill the whole containing width.
No. You were right, the absolute positioning was not necessary.
I had:
position: absolute;
left: 0px;
right: 0px;
margin-left: auto;
margin-right: auto;
width: 100px;
to centre a box with the width set to 100px. This works just as well:
margin-left: auto;
margin-right: auto;
width: 100px;
Easy, because the width is known to be 100px. No need for absolute
positioning. The OP said that the width was 100px, so that's fine.
But can we centre a shrink-to-fit box? I actually don't think it's
possible (without JS or a table).
Absolutely positioned boxes are shrink-to-fit if they have auto width,
but not if you try to centre them with auto margins. For example:
position: absolute;
left: 0px;
right: 0px;
margin-left: auto;
margin-right: auto;
width: auto;
will fill the full containing width, because the UA solves for width
such that left + width + right = containing width and leaves the margins
at 0.
The only condition under which a positioned box is centred is if left,
right and width are _all_ set to something, but left and right margins
are both auto. These are the CSS rules. There's no way to say we want
the shrink-to-fit width, and equal space either side.
The table solution is this:
<table style="width: 100%">
<td style="width: 50%">
</td>
<td style="border: 1px solid black">
Hello
</td>
<td style="width: 50%">
</td>
</table>
"Hello" is shrink-to-fit and centered.
[Back to original message]
|