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

如何将表单在表单容器中垂直居中?(优先采用Flexbox方案)

解决表单垂直居中问题(Flexbox方案)

你的问题出在.form-container的height: 100%设置上——它会让这个容器撑满父元素.container的高度,直接抵消了.container上align-items: center的垂直居中效果。另外CSS里的hmtl是拼写错误,得修正。

按照你的需求,保留原有结构的前提下,用Flexbox修改如下:

修改后的CSS代码

html,
body {
  height: 100%;
  width: 100%;
  background-color: wheat;
  overflow: hidden;
  margin: 0;
}

.container {
  display: flex;
  gap: 200px;
  align-items: center; /* 让子元素垂直居中 */
  height: 100%;
  width: 100%;
}

.form-container {
  display: flex;
  width: 100%;
  justify-content: center; /* 水平居中表单 */
  /* 移除height:100%,让容器高度自适应内容 */
}

.main-image {
  height: 1200px;
  width: 900px;
}

#main-Form {
  /* 这里可以保留margin:auto,不过.form-container的flex布局已经能让它水平居中 */
}

修改后的HTML代码(结构无变化)

<div class="container">
  <div class="image-container">
    <img class="main-image" src="./static/images/30daysreplay-social-media-marketing-3_a7s0MAXhc-unsplash (1).jpg" alt="">
  </div>
  <div class="form-container">
    <form id="main-Form">
      <input type="email" name="email-input" id="">
      <input type="text" name="username" id=""> <!-- 修正:无type="username",标准类型为text -->
    </form>
  </div>
</div>

额外说明

  • 顺便修正了HTML里的输入框类型:type="username"不是标准属性,正确的用户名输入框应该用type="text"
  • 如果之后需要.form-container保持100%高度,同时让表单在容器内部垂直居中,只需给.form-container补充一行属性:
    .form-container {
      display: flex;
      height: 100%;
      width: 100%;
      justify-content: center;
      align-items: center; /* 新增:让表单在容器内垂直居中 */
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:40:42