如何构建灵活的HTML表单布局?

时间:2016-03-29 15:15:32

标签: html css layout html-form css-frameworks

我想构建一个灵活的html表单,其中包含以下功能:

  1. 标签应该保持在他的组件正上方(见下图);
  2. 组件应填充(宽度尺寸)屏幕上可用的所有空间,并配置最小宽度;
  3. 如果屏幕宽度不适合所有表单组件,则应将它们堆叠起来;
  4. HTML Form with components filling all screen width
    HTML表单,其中的组件填充所有屏幕宽度

    Same HTML Form with reduced screen width
    屏幕宽度缩小的相同HTML表单

    如果不使用html表而只使用HTML + CSS,那么实现此结果的更优雅的解决方案是什么?

2 个答案:

答案 0 :(得分:1)

这应该这样做:



.form-group {
    float: left;
    width: 100%;
}

.form-control {
    padding: 3px;
    box-sizing: border-box;
    float: left;
}

.form-control input,
.form-control select,
.form-control textarea {
    box-sizing: border-box;
    width: 100%;
}

.form-control textarea {
    resize: vertical;
}

#form-group-1 .form-control {
    width: 33.333%;
}

#form-group-2 .form-control {
    width: 50%;
}

#form-group-3 .form-control {
    width: 100%;
}

#form-group-4 .form-control {
    width: 6em;
}

@media (max-width: 500px) {
    #form-group-1 .form-control {
        width: 50%;
    }
    
    #form-group-2 .form-control {
        width: 66.6666%;
    }
}

<form>
    <div class="form-group" id="form-group-1">
        <div class="form-control">
            <label for="field1">Field 1</label>
            <input name="field1" id="field1" placeholder="text1">
        </div>
        <div class="form-control">
            <label for="field2">Field 2</label>
            <input name="field2" id="field2" placeholder="text2">
        </div>
        <div class="form-control">
            <label for="field3">Field 3</label>
            <select name="field3" id="field3">
               <option value="1">Option 1</option>
               <option value="2">Option 2</option>
            </select>
        </div>
    </div>
    <div class="form-group" id="form-group-2">
        <div class="form-control">
            <label for="field4">Field 4</label>
            <input name="field4" id="field4" placeholder="text4">
        </div>
        <div class="form-control">
            <label for="field5">Field 5</label>
            <input name="field5" id="field5" placeholder="text5">
        </div>
    </div>
    <div class="form-group" id="form-group-3">
        <div class="form-control">
            <label for="field6">Field 6</label>
            <textarea name="field6" id="field6"></textarea>
        </div>
    </div>
    <div class="form-group" id="form-group-4">
        <div class="form-control">
            <input type="submit" value="OK" />
        </div>
        <div class="form-control">
            <input type="button" value="CANCEL" />
        </div>
    </div>
</form>
&#13;
&#13;
&#13;

(另见this Fiddle

答案 1 :(得分:1)

Enter

这就是你想要的,通过使用最好的方式完成,使用bootstrap,你需要练习bootstrap,在这里参考你可以去Bootstrap forms。快乐的编码!