CSS 将 `<fieldset>` 的宽度设置为最大包含元素的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4022057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:02:49  来源:igfitidea点击:

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

css

提问by ziiweb

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

有没有办法让 a<fieldset>的宽度成为其中最大字段的宽度?

采纳答案by Justus Romijn

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

你的意思是这样的: jsFiddle fieldset 是最大的包含 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.

它是一个浮动字段集。如果您想要其他方式,请告诉我们。

回答by álvaro González

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:

只需将您的问题放在一般背景下即可。A<fieldset>是一个块元素,因此它的默认行为是扩展以填充可用的水平空间。所以你基本上有两个选择:

  1. Set a new explicit width.
  2. Change its layout from blockto something else.
  1. 设置一个新的显式宽度。
  2. 将其布局从更改block为其他内容。

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.

更新:我忘了提到浮动块级元素也会改变其布局。