Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the width of a `<fieldset>` to the width of the largest containing element

Tags:

css

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

like image 568
ziiweb Avatar asked Oct 26 '10 08:10

ziiweb


2 Answers

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">
<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.

like image 165
Álvaro González Avatar answered Oct 11 '22 03:10

Álvaro González


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

<form action="#" id="test" name="test">
    <fieldset>
        <input type="text" class="first" />
        <input type="text" class="second" />
        <input type="text" class="third" />

    </fieldset>

</form>

fieldset{
    overflow: hidden;
    float: left;
    background-color: #eee;
}
input {
    display: block;
}
input.first{ width: 150px; }
input.second{ width: 200px; }
input.third { width: 250px; }

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

like image 31
Justus Romijn Avatar answered Oct 11 '22 02:10

Justus Romijn