views:

276

answers:

3

I am little bit tired for now (out of coffee), so I am unable to figure this out.

When I set p.style.width = auto (the blue one), why is its width at 100%? None of the elements have their width set to 100%, so I doubt it's inherited property.

How can I set the <p>'s width to match its content width plus padding?

Sample page: http://elijen.ic.cz/hs

+2  A: 

Because width:auto defaults to 100% (that is, minus borders and paddings, see here), if you are not in a floating/positioned environment. Actually, without

float:left

or

position: absolute

you're quite out of luck setting the width of an element to a minimum in CSS only. See, e.g., here for how you could achieve it in Firefox (only).

Edit: You could also use

display: table;
width: auto;

but for one this is also not supported in all browsers and then the table design may bring you in all kinds of other trouble.

Edit 2: You might, as suggested by DisgruntledGoat, also try display:inline-block. This page gives a cross-browser implementation targeting IE6+, FF2+, Safari 3+ and Opera.

Boldewyn
That's strange behaviour. I would expect width:auto means width = (sum of children widths + padding).I think I'll use the position: absolute here, but how could I achieve the same with relative positioned element without float? (cross-browser) There is no clear solution available?
Petr Peller
Unfortunately, this field is as tricky as, e.g., vertically centered content. Try one of the solutions (of the other answers as well), and in 99% of all cases you find one that is ok for your design. In all other cases, JavaScript is a necessary friend.
Boldewyn
+1  A: 

It's all explained in the spec

http://www.w3.org/TR/CSS2/visudet.html#blockwidth

O.O

Essentially, auto means taking all the other specified paddings, borders and margins into account fill the remaining space (assuming only the width is set to auto). So effectively 100% minus borders, padding and margins.

To fix, just set it to match the other elements, or stick them all in a containing element with a set width.

fd
+1  A: 

The others are right, width: auto sets the width to fill all available space.

One solution would be to use display: inline-block, which should do what you want. For compatibility with IE6 it's best to apply that to an inline element like <span>. And add display: -moz-inline-box for Firefox 2 and earlier.

DisgruntledGoat