tags:

views:

21

answers:

2

Is there any way to have the width of a <fieldset> be the width of the largest field inside it?

+2  A: 

Do you mean this: jsFiddle fieldset that is wide as biggest containing input-element

It is a floating fieldset. If you want it in another way, please let us know.

Justus Romijn
Even works in IE6. Nice.
Pekka
@Pekka As always: make the magic of overflow:hidden; do the trick for you :)
Justus Romijn
A: 

Just put your question in a general context. A <fieldset> is a block element, thus its default behaviour is to expand to fill the available horizontal space. So you basically have two options:

  1. Set a new explicit width.
  2. Change its layout from block to something else.

Here's a quick example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css"><!--
fieldset.explicit-width{
    width: 1%; /* Will expand to fit content */
}
fieldset.inline-block{
    display: inline-block;
}
--></style>
</head>
<body>

<fieldset><legend>Unstyled</legend>
    <p><input type="text" size="2"></p>
    <p><input type="text" size="20"></p>
    <p><input type="text" size="50"></p>
    <p><input type="text" size="30"></p>
</fieldset>

<fieldset class="explicit-width"><legend>Explicit width</legend>
    <p><input type="text" size="2"></p>
    <p><input type="text" size="20"></p>
    <p><input type="text" size="50"></p>
    <p><input type="text" size="30"></p>
</fieldset>

<fieldset class="inline-block"><legend>Inline-block</legend>
    <p><input type="text" size="2"></p>
    <p><input type="text" size="20"></p>
    <p><input type="text" size="50"></p>
    <p><input type="text" size="30"></p>
</fieldset>

</body>
</html>

Update: I forgot to mention that floating a block-level element also changes its layout.

Álvaro G. Vicario