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

如何将label对齐到input上方?附表单代码求助

表单样式调整:实现Label在Input上方对齐

我有一段表单代码,想要实现Label在Input上方的对齐效果,和下图样式一致,但不知道怎么设置样式,求帮忙。

表单目标样式

原代码片段

CSS代码

form {
  background-color: white;
  width: 800px;
}

/* label,input{
        display:flex;
        flex-direction:row;
      }
    form input{
        display: flex;
        flex-direction: column;
        padding: 10px;
        border-radius: 5px;
        border: 1px solid white;
    } */

form button {
  color: white;
  background-color: rgb(9, 63, 228);
  width: 150px;
  padding: 10px;
  border-radius: 5px;
}

HTML代码

<form>
  <label for="go">Where You Want to go</label>
  <input type="text" id="go" name="go" placeholder="Search your location" required minlength="6">
  <br>
  <label for="indate">Check-in</label>
  <input type="date" id="indate" name="indate" placeholder="Add Date" required><br>
  <label for="outdate">Check-out</label>
  <input type="date" id="outdate" name="outdate" placeholder="Add Date" required><br>
  <button>Explore Now</button>
</form>

解决方案

要实现Label在Input上方的布局,推荐把每个label和对应的input包裹在独立容器中,用Flex布局让它们垂直排列,同时优化整体排版,让输入框宽度统一、间距更合理。

修改后的完整代码

CSS部分

form {
  background-color: white;
  width: 800px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px; /* 控制表单组之间的间距 */
}

/* 表单组容器:包裹单个label和input */
.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px; /* label与input的间距 */
}

.form-group label {
  font-weight: 500;
  color: #333;
}

.form-group input {
  padding: 10px;
  border-radius: 5px;
  border: 1px solid #ddd;
  font-size: 16px;
}

form button {
  color: white;
  background-color: rgb(9, 63, 228);
  width: 150px;
  padding: 10px;
  border-radius: 5px;
  border: none;
  cursor: pointer;
  align-self: flex-start; /* 按钮靠左对齐 */
}

HTML部分

<form>
  <div class="form-group">
    <label for="go">你想去哪里</label>
    <input type="text" id="go" name="go" placeholder="搜索你的目的地" required minlength="6">
  </div>
  
  <div class="form-group">
    <label for="indate">入住日期</label>
    <input type="date" id="indate" name="indate" required>
  </div>
  
  <div class="form-group">
    <label for="outdate">退房日期</label>
    <input type="date" id="outdate" name="outdate" required>
  </div>
  
  <button>立即探索</button>
</form>

关键调整说明

  • 新增.form-group容器,通过flex-direction: column让label自然排列在input上方;
  • 用gap属性替代<br>控制间距,布局更灵活可控;
  • 统一输入框样式,添加边框提升视觉清晰度;
  • 按钮设置align-self: flex-start靠左对齐,贴近目标样式的排版逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:00:19