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

如何实现输入框横向排列且标签置于输入框上方?

解决方案

要实现标签在输入框上方、输入框横向排列的效果,你需要将每个标签和输入框组合成独立的垂直容器,再将这些容器横向排列。以下是具体实现方式:

1. 修改HTML结构

给每组label和input包裹一个容器(比如<div class="input-field">),这样可以单独控制每组的垂直布局:

<main>
  <section class="wrap">
    <section class="inputs">
      <div class="input-field">
        <label for="day">DAY</label>
        <input type="number" name="day" id="day" placeholder="DD">
      </div>
      <div class="input-field">
        <label for="month">MONTH</label>
        <input type="number" name="month" id="month" placeholder="MM">
      </div>
      <div class="input-field">
        <label for="year">YEAR</label>
        <input type="number" name="year" id="year" placeholder="YYYY">
      </div>
    </section>

    <div id="line"></div>

    <p><span class="purple"> -- </span>years</p>
    <p><span class="purple"> -- </span>months</p>
    <p><span class="purple"> -- </span>days</p>
  </section>
</main>

2. 添加样式实现布局

方式一:自定义CSS

通过Flex布局实现横向排列的组,每组内部垂直排列:

/* 横向排列所有输入组 */
.inputs {
  display: flex;
  flex-direction: row;
  gap: 15px; /* 调整组之间的间距 */
}

/* 每组内部标签在上,输入框在下 */
.input-field {
  display: flex;
  flex-direction: column;
  gap: 5px; /* 标签和输入框之间的间距 */
}

/* 保留你原有的样式 */
label {
  font-family: 'Poppins', sans-serif;
  font-size: .6em;
  letter-spacing: 5px;
}

input {
  width: 130px;
  height: 60px;
  border-radius: 5px;
  border: var(--Smokey-grey) solid 1px;
  padding: 20px;
}

方式二:使用Bootstrap工具类

如果你想利用Bootstrap的内置样式,无需额外写CSS,直接给容器添加对应的类:

<main>
  <section class="wrap">
    <section class="inputs d-flex flex-row gap-4">
      <div class="input-field d-flex flex-column gap-2">
        <label for="day">DAY</label>
        <input type="number" name="day" id="day" placeholder="DD">
      </div>
      <div class="input-field d-flex flex-column gap-2">
        <label for="month">MONTH</label>
        <input type="number" name="month" id="month" placeholder="MM">
      </div>
      <div class="input-field d-flex flex-column gap-2">
        <label for="year">YEAR</label>
        <input type="number" name="year" id="year" placeholder="YYYY">
      </div>
    </section>

    <div id="line"></div>

    <p><span class="purple"> -- </span>years</p>
    <p><span class="purple"> -- </span>months</p>
    <p><span class="purple"> -- </span>days</p>
  </section>
</main>

用到的Bootstrap核心类:

  • d-flex:启用Flex布局
  • flex-row:横向排列子元素
  • flex-column:纵向排列子元素
  • gap-4/gap-2:设置元素间的间距(数值对应Bootstrap的间距刻度)

原理说明

  • 外层.inputs用横向Flex布局,让三个输入组并排展示
  • 每个.input-field用纵向Flex布局,确保组内标签始终在输入框上方

内容的提问来源于stack exchange,提问作者T.K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:30:45