You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bootstrap 5中实现label标签与input输入框同行对齐

Bootstrap 5 label与input同行显示实现方法

你可以借助Bootstrap 5自带的栅格系统实现该效果,具体修改如下:

  • 给每个包裹label、input的mb-3容器添加row类,启用行栅格布局
  • 给label标签添加col-form-label类保证垂直居中,同时指定栅格宽度,比如col-sm-2
  • 给input外层套一个栅格容器,比如col-sm-10,和label的栅格占比相加为12即可,你原本设置的input宽度40%可以直接在这个容器上控制
  • 提示类文本form-text要放在input所在的栅格容器内,避免排版错位

修改后的完整代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>HTML CSS JS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  </head>
  <body>
    <div class="container pt-5">
      <form (ngSubmit)="login()">
        <div class="row mb-3 align-items-center">
          <label for="exampleInputEmail1" class="col-sm-2 col-form-label">User</label>
          <div class="col-sm-10">
            <input type="text" class="form-control" name="exampleInputEmail1" style="width: 40%" aria-describedby="emailHelp" [(ngModel)]="loginForm.user" required maxlength="4">
            <div id="emailHelp" class="form-text">我们绝不会向他人泄露您的邮箱信息。</div>
          </div>
        </div>
        <div class="row mb-3 align-items-center">
          <label for="exampleInputPassword1" class="col-sm-2 col-form-label">Password</label>
          <div class="col-sm-10">
            <input type="password" class="form-control" name="exampleInputPassword1" style="width: 40%" [(ngModel)]="loginForm.password" required maxlength="4">
          </div>
        </div>
        <button type="submit" class="btn btn-primary">登录</button>
      </form>
    </div>
  </body>
</html>

如果需要适配小屏幕自动换行,直接调整栅格的断点即可,比如把col-sm-2改成col-md-2,就会在中等宽度以下的屏幕自动变成上下布局。

内容的提问来源于stack exchange,提问作者user17074809

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:15:00