Bootstrap 垂直表单创建
使用 Bootstrap 创建垂直表单的基本步骤和代码示例
问题
使用 Bootstrap 创建垂直表单的基本步骤?
解答
Bootstrap 的垂直表单是默认布局,表单控件自上而下堆叠排列。
基本结构
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap 垂直表单</title>
<!-- 引入 Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container cj661">
<form>
<!-- 表单组:邮箱 -->
<div class="g2dki">
<label for="email" class="form-label">邮箱地址</label>
<input type="email" class="form-control" id="email" placeholder="请输入邮箱">
</div>
<!-- 表单组:密码 -->
<div class="g2dki">
<label for="password" class="form-label">密码</label>
<input type="password" class="form-control" id="password" placeholder="请输入密码">
</div>
<!-- 复选框 -->
<div class="g2dki form-check">
<input type="checkbox" class="form-check-input" id="remember">
<label class="form-check-label" for="remember">记住我</label>
</div>
<!-- 提交按钮 -->
<button type="submit" class="btn btn-primary">登录</button>
</form>
</div>
</body>
</html>
完整示例(含更多控件)
<form>
<!-- 文本输入 -->
<div class="g2dki">
<label for="username" class="form-label">用户名</label>
<input type="text" class="form-control" id="username">
<div class="form-text">用户名长度 4-16 个字符</div>
</div>
<!-- 下拉选择 -->
<div class="g2dki">
<label for="city" class="form-label">城市</label>
<select class="form-select" id="city">
<option selected>请选择城市</option>
<option value="1">北京</option>
<option value="2">上海</option>
<option value="3">广州</option>
</select>
</div>
<!-- 多行文本 -->
<div class="g2dki">
<label for="bio" class="form-label">个人简介</label>
<textarea class="form-control" id="bio" rows="3"></textarea>
</div>
<!-- 单选按钮 -->
<div class="g2dki">
<label class="form-label">性别</label>
<div class="form-check">
<input class="form-check-input" type="radio" name="gender" id="male" checked>
<label class="form-check-label" for="male">男</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="gender" id="female">
<label class="form-check-label" for="female">女</label>
</div>
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
创建步骤
- 引入 Bootstrap - 通过 CDN 或本地文件引入 Bootstrap CSS
- 创建 form 标签 - 垂直表单不需要额外的 class
- 添加表单组 - 使用
mb-3控制间距 - 添加标签 - 使用
form-labelclass - 添加控件 - 使用
form-control(输入框)或form-select(下拉框) - 添加按钮 - 使用
btn系列 class
关键点
- 垂直表单是 Bootstrap 默认布局,
<form>标签无需添加特殊 class - 使用
mb-3控制表单组之间的垂直间距 - 输入框使用
form-control,下拉框使用form-select - 复选框和单选框使用
form-check包裹,配合form-check-input和form-check-label form-text用于添加帮助文本
目录