如何在 CSS 中并排获得两个表单字段,每个字段的标签位于字段上方?

新手上路,请多包涵

我坚持找出一些 css,我需要我的表单的一部分如下所示,

CSS 向左浮动

我已经尝试了所有我能想到的变化,

我给标签一个固定的宽度并将它们向左浮动,然后给输入相同的宽度并将它们向左浮动。

我完全没有想法,请问我该如何实现?

原文由 sea_1987 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 734
2 个回答
<form>
  <label for="company">
    <span>Company Name</span>
    <input type="text" id="company" />
  </label>
  <label for="contact">
    <span>Contact Name</span>
    <input type="text" id="contact" />
  </label>
</form>

label { width: 200px; float: left; margin: 0 20px 0 0; }
span { display: block; margin: 0 0 3px; font-size: 1.2em; font-weight: bold; }
input { width: 200px; border: 1px solid #000; padding: 5px; }

插图在 http://jsfiddle.net/H3y8j/

原文由 user527892 发布,翻译遵循 CC BY-SA 3.0 许可协议

布局中的每一列都需要一个 HTML 元素。

我建议:

HTML

 <div class="two-col">
    <div class="col1">
        <label for="field1">Field One:</label>
        <input id="field1" name="field1" type="text">
    </div>

    <div class="col2">
        <label for="field2">Field Two:</label>
        <input id="field2" name="field2" type="text">
    </div>
</div>

CSS

 .two-col {
    overflow: hidden;/* Makes this div contain its floats */
}

.two-col .col1,
.two-col .col2 {
    width: 49%;
}

.two-col .col1 {
    float: left;
}

.two-col .col2 {
    float: right;
}

.two-col label {
    display: block;
}

原文由 Paul D. Waite 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题