On 2007-05-23, Gérard Talbot <ne***********@ gtalbot.orgwrot e:
biff wrote :
>lister wrote:
>>I am trying to center a DIV horizonally, but I want the DIV fluid so
that it is just wide enough to encompass its contents.
I've tried margin:auto with no joy :(
I've set up a demo here:
http://www.thebunnyshed.co.uk/centertest.htm
ps. google screwed up my first post somehow.
you also need to set a width
The OP wants the div to stretch laterally, to expand horizontally to
fit/meet the width of its inline content ("just wide enough to encompass
its contents"). So, inline-block has to be a serious option here.
"inline-block
This value causes an element to generate a block box, which itself
is flowed as a single inline box, similar to a replaced element. The
inside of an inline-block is formatted as a block box, and the element
itself is formatted as an inline replaced element."
http://www.w3.org/TR/CSS21/visuren.html#propdef-display
or the div
>you are using for a container will take up the width of the entire outer
container... .
I believe his best chance is to use
div {display: inline-block; display: -moz-inline-block; margin-left:
auto; margin-right: auto;}
Inline-block is the best way to do this, or would be if it were
supported by more browsers. But the way to centre it is not with auto
margins, but with text-align: center on the container.
See CSS 2.1 10.3.9-- auto left and right margins on inline blocks are
treated as zero. You only get that centering behaviour with block boxes.
Inline blocks are like inlines from the point of view of their
container, but like blocks from the point of view of their descendents.
So you center them like inlines, with text-align: center on their
container, rather than like blocks, which you centre with auto margins.
e.g.
body { text-align: center; }
div
{
display: inline-block;
display: -moz-inline-box; /* seems to work here */
border: 2px solid green;
}
<body>
<div>hello</div>
</body>
works in Opera.
The problem with inline-block is that IE (I heard) doesn't do the one
feature you need here, which is shrink-to-fit width. I don't know about
-moz-inline-box (it's -moz-inline-box, not -moz-inline-block) but it
seems to work OK in this example.