我有一个固定宽度的 div,它包含三个 id 为“first”、“second”、“third”的字段集:
现在我希望它们的位置如下:第一个字段集在左边,第二个在中间,第三个在右边。我希望他们即使在一个或所有其他人被隐藏时也能留在自己的位置上,而不使用绝对或固定位置。
在向您展示我已经尝试过的内容之前,我会给您一些代码。 HTML 优先:
<div class="container_options">
<fieldset class="fieldset_first" id="first">
<legend>Konfiguration des offenen Endes</legend>
</fieldset>
<fieldset class="fieldset_second" id="second">
<legend>Verfügbare Optionen für Ihr Kabel</legend>
</fieldset>
<fieldset class="fieldset_third" id="third">
<legend>Konfiguration des offenen Endes</legend>
</fieldset>
</div>
现在的 CSS:
div.container_options {
margin: 15px;
clear: both;
width: 980px;
}
fieldset.fieldset_first{
width: 300px;
border: 1px solid black;
border-radius: 5px;
margin-left: 0;
margin-right: auto;
float: left;
margin-top: 10px;
}
.fieldset_first legend {
font-weight: bold;
}
.fieldset_third{
width: 300px;
border: 1px solid black;
border-radius: 5px;
margin-left: auto;
margin-right: 0;
float: right;
margin-top: 10px;
}
.fieldset_third legend {
font-weight: bold;
}
.fieldset_second {
width: 300px;
border: 1px solid black;
border-radius: 5px;
margin: auto;
float: right;
float: left;
margin-top: 10px;
}
您可以在以下JSFiddle 中测试此代码可以隐藏/显示字段集以查看它们的行为方式。
现在我来解决问题:
当显示所有三个字段集时,一切正常。
如果我隐藏正确的那个,一切都很好。
如果我隐藏左边的,中间的会跳到左边并且不关心 margin: auto;
我在 Stackoverflow 上发现了一些类似的问题:
CSS: Positioning components using margins
div won't center with margin: 0 auto;
CSS Positioning Margin Trouble
我尝试了对他们有用的方法,但它们似乎对我不起作用。例如,一个答案说我不应该在尝试使用 margin 定位时使用 float
属性。我创建了另一个 JSFiddle我尝试这样做的地方,但结果不是我想要的。我做错了什么?
最佳答案
第二个JSFIDDLE如果您为所有字段集提供 display: inline-block;
样式,则可以使用。
fieldset.main_options_plug1{
width: 300px;
border: 1px solid black;
border-radius: 5px;
margin-left: 0;
margin-right: auto;
/* float: left; */
margin-top: 10px;
display: inline-block;
vertical-align: top;
visibility: hidden;
}
然后,当您想要隐藏其中一个字段集时,您不能使用 display: none;
,因为这将从文档流中删除该元素。使用 visibility: hidden;
代替。
关于javascript - 使用边距在 CSS 中定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20516089/