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

如何在React+HTML/CSS登录表单中对齐标签与输入框

解决方案:登录表单标签与输入框对齐 + 布局调整

问题说明

我正在用HTML/CSS(实际是React项目)编写登录表单UI,目前无法让表单位于标题下方,同时让「Your email」「Your password」标签与输入框的起始端对齐。当前效果为标签和输入框居中但起始端错位,期望效果是标签与输入框左对齐,整体表单在标题下方规整排列。

现有代码

CSS 代码

.login-form { width: 60%; margin: 250px auto; padding: 25px; border: 3px solid darkcyan; }
.login-form h2 { text-align: center; }
.login-form .form { text-align: center; }
.form-group p { margin-bottom: 5px; }
.form-group input { width: 30%; height: 30px; }
.form-group .button { width: 10%; height: 30px; margin-top: 15px; }

React JSX 代码

<div className="container">
  <div className="login-form">
    <h2>Login here</h2>
    <form className='form'>
      <div className="form-group">
        <p>Your email</p>
        <input type='text' name='email' id='email' placeholder='Email' />
      </div>
      <div className="form-group">
        <p>Your password</p>
        <input type='password' name='password' id='password' placeholder='Password' />
      </div>
      <div className="form-group">
        <input type='submit' name='login' id='login' value='Login' className="button" />
      </div>
    </form>
  </div>
</div>

修改方案

核心问题是.login-form .form的text-align: center导致表单内容居中,且标签与输入框宽度不一致,无法对齐。以下是两种可行修改方式:

方式一:Flex 布局实现(推荐)

调整CSS代码如下:

.login-form {
  width: 60%;
  margin: 250px auto;
  padding: 25px;
  border: 3px solid darkcyan;
}
.login-form h2 {
  text-align: center; /* 标题保持居中 */
}
.login-form .form {
  /* 用flex让表单组水平居中,内部内容左对齐 */
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px; /* 表单组之间的间距 */
}
.form-group {
  width: 30%; /* 和输入框目标宽度一致 */
}
.form-group p {
  margin: 0 0 5px 0;
}
.form-group input {
  width: 100%; /* 输入框占满表单组宽度 */
  height: 30px;
  box-sizing: border-box; /* 避免边框/内边距溢出宽度 */
}
.form-group .button {
  width: 100%; /* 按钮统一宽度,也可按需调整为固定值 */
  height: 30px;
  margin-top: 5px;
}

方式二:传统块级布局实现

如果不想用Flex,也可以通过调整表单组的外边距实现:

.login-form {
  width: 60%;
  margin: 250px auto;
  padding: 25px;
  border: 3px solid darkcyan;
}
.login-form h2 {
  text-align: center;
}
.login-form .form {
  text-align: left; /* 移除原居中设置,改为左对齐 */
}
.form-group {
  width: 30%;
  margin: 0 auto 15px; /* 水平居中,底部添加间距 */
}
.form-group p {
  margin: 0 0 5px 0;
}
.form-group input {
  width: 100%;
  height: 30px;
  box-sizing: border-box;
}
.form-group .button {
  width: 100%;
  height: 30px;
}

修改效果

两种方式都能实现:

  • 标题保持居中
  • 「Your email」「Your password」标签与输入框起始端完全对齐
  • 整体表单在标题下方规整排列,符合期望效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:45:41