如何使用类使用CSS将无表格HTML表单呈现为两列?

时间:2015-09-05 19:11:46

标签: html css forms layout

我正在尝试格式化双列表单,以便:

  • 标签位于每个输入字段或文本区域
  • 之上
  • 班级 col1 中的所有内容都在左侧列中
  • 班级 col2 中的所有内容都在右侧的列中
  • 班级中的所有内容 col12 跨越两列

以下是我需要使用的HTML代码:

    <div id="contactForm">
      <form method="post" action="">
        <h3>Contact us</h3>
        <p>To send us a work order, fill in the form below.<br /><strong>All the (*) fields are mandatory.</strong></p>
        <fieldset>
          <div class="col1">
            <label for="form_firstname">Firstname <span class="required">*</span></label>
            <input type="text" id="form_firstname" name="form_firstname" value="" />
          </div>
          <div class="col2">
            <label for="form_lastname">Lastname <span class="required">*</span></label>
            <input type="text" id="form_lastname" name="form_lastname" value="" />
          </div>
          <div class="col1">
            <label for="form_address">Address</label>
            <input type="text" id="form_address" name="form_address" value="" />
          </div>
          <div class="col2">
            <label for="form_city">City</label>
            <input type="text" id="form_city" name="form_city" value="" />
          </div>
          <div class="col1">
            <label for="form_email">Email <span class="required">*</span></label>
            <input type="text" id="form_email" name="form_email" value="" />
          </div>
          <div class="col2">
            <label for="form_phone">Phone <span class="required">*</span></label>
            <input type="text" id="form_phone" name="form_phone" value="" />
          </div>
          <div class="col12">
            <label for="form_attachment">Add Attachment <span class="form_attachment">*</span></label>
            <textarea id="form_attachment" name="form_attachment" rows="5"></textarea>
          </div>
          <div class="col12">
            <label for="form_message">Message <span class="required">*</span></label>
            <textarea id="form_message" name="form_message" rows="5"></textarea>
          </div>
          <div class="col12">
            <label for="form_message">Message <span class="required">*</span></label>
            <input type="submit" value="Send" formnovalidate="formnovalidate" />
          </div>
        </fieldset>
      </form>
    </div>

如何根据需要对CSS进行编码以设置此HTML样式?

以下是JSFiddle上的代码。

1 个答案:

答案 0 :(得分:1)

试试这个CSS:

#contactForm{
    width: 80%;
}
label,.col1,.col2,.col12{display: block;}
.col1{ float:right;}
.col2{float:left;}
.col12{clear:both;}
textarea{
    display: block;
    width: 100%;
}

http://jsfiddle.net/rx2gjpdw/3/