如何居中HTML表单元素(标签、输入框、按钮)以对齐页面标题
问题描述
我开发了一款支持多字段筛选的食谱搜索表单,用户可通过3类条件细化搜索范围。目前需要将表单内的标签、下拉选择框、文本输入框、提交按钮等元素,与已经设置为居中的页面引导标题对齐,但尝试多种实现方法后始终达不到预期的居中效果,无法定位问题原因。
以下是我当前的代码:
<p style="text-align:center">查看符合以下条件的食谱:</p> <div class="container cols justify-content center"> <div style="margin-bottom: 30px; width: 300px;"> <label for="author">按作者筛选:</label> <select name="author" id="author"> <option value="">任意作者</option> <?php foreach ($authors as $author): ?> <option value="<?php html($author['id']);?>"><?php html($author['name']);?></option> <?php endforeach;?> </select> </div> <div style="margin-bottom: 30px; width: 300px;"> <label for="category">按分类筛选:</label> <select name="category" id="category"> <option value="">任意分类</option> <?php foreach ($categories as $category): ?> <option value="<?php html($category['id']);?>"><?php html($category['name']);?></option> <?php endforeach;?> </select> </div> <div style="margin-bottom: 30px; width: 300px;"> <label for="text">包含关键词:</label> <input type="text" name="text" id="text"> </div> <div style="margin-bottom: 30px; width: 300px;"> <input class="btn btn-primary" type="submit" name="action" value="搜索"> </div> </div> </form> </div>
问题原因
居中失效核心是4点错误:
- 外层容器的
justify-content center是错误写法,且没有声明flex布局,所有flex相关的类完全不生效 - 就算开启flex,默认是横向排列模式,你需要的表单元素垂直堆叠效果需要单独设置纵向flex方向
- 每个表单子块内部的元素默认左对齐,就算子块在外层居中,块内的标签、输入框也无法和上方的居中标题对齐
- 额外:代码开头缺失了
<form>起始标签,会导致表单提交逻辑异常
修复方案
直接使用内联样式、不依赖任何类库的完整可运行代码如下:
<!-- 补全form起始标签 --> <form> <p style="text-align:center">查看符合以下条件的食谱:</p> <!-- 外层容器声明纵向flex、整体子元素居中 --> <div style="display: flex; flex-direction: column; align-items: center;"> <!-- 子块增加text-align:center让内部元素居中,输入类元素设置宽度100%统一对齐 --> <div style="margin-bottom: 30px; width: 300px; text-align: center;"> <label for="author">按作者筛选:</label> <select name="author" id="author" style="width: 100%; margin-top: 5px;"> <option value="">任意作者</option> <?php foreach ($authors as $author): ?> <option value="<?php html($author['id']);?>"><?php html($author['name']);?></option> <?php endforeach;?> </select> </div> <div style="margin-bottom: 30px; width: 300px; text-align: center;"> <label for="category">按分类筛选:</label> <select name="category" id="category" style="width: 100%; margin-top: 5px;"> <option value="">任意分类</option> <?php foreach ($categories as $category): ?> <option value="<?php html($category['id']);?>"><?php html($category['name']);?></option> <?php endforeach;?> </select> </div> <div style="margin-bottom: 30px; width: 300px; text-align: center;"> <label for="text">包含关键词:</label> <input type="text" name="text" id="text" style="width: 100%; margin-top: 5px;"> </div> <div style="margin-bottom: 30px; width: 300px; text-align: center;"> <input class="btn btn-primary" type="submit" name="action" value="搜索"> </div> </div> </form>
如果使用Bootstrap类库开发,可将上述内联样式替换为对应类名:
- 外层容器的类改为:
container d-flex flex-column align-items-center - 每个表单子块追加
text-center类
内容的提问来源于stack exchange,提问作者Mannan
相关产品推荐
相关产品推荐

