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

如何为Thymeleaf页面的内联<select>元素应用Bootstrap 5样式?

解决方案

问题的核心原因是Bootstrap 5中form-select类默认宽度为100%,直接添加会撑满父容器整行,只需要用Bootstrap自带的工具类调整即可,无需自定义样式:

调整步骤

  • 替换已废弃的form-inline类:Bootstrap 5已经移除了form-inline,给外层容器添加d-flex align-items-center gap-2,实现横向排列、垂直居中,同时增加元素之间的间距
  • 给三个年/月/日下拉框添加类:form-select form-select-sm w-auto,其中w-auto会把下拉框宽度调整为自适应内容宽度,不会撑满整行

修改后的代码片段

<main role="main" class="pb-3">
  <br>
  <p>Post office expenses</p>
  <div class="row">
    <!-- 替换原form-inline为flex布局类 -->
    <div class="d-flex align-items-center gap-2 ms-2">
      <div class="form-group d-flex align-items-center gap-2">
        <span>Year:</span>
        <!-- 新增form-select相关类和w-auto -->
        <select class="form-select form-select-sm w-auto" id="selectYear" th:field="*{years}" onchange="getDaysInMonth()">
          <option th:each="y : ${years}" th:value="${y}" th:text="${y}" />
        </select>
        <span>Month:</span>
        <select class="form-select form-select-sm w-auto" id="selectMonth" th:field="*{monthsList}" onchange="getDaysInMonth()">
          <option th:each="m : ${monthsList}" th:value="${m.id}" th:text="${m.monthName}" />
        </select>
        <span>Day:</span>
        <select class="form-select form-select-sm w-auto" name="selectDay" id="selectDay">
          <option th:each="n : ${#numbers.sequence(1,31)}" th:value="${n}" th:text="${n}"/>
        </select>
      </div>       
    </div>
  </div>
  <!-- 下方原有代码保持不变即可 -->
  <div class="row pt-3">
      <div class="col-2">
          <form>
              <div class="form-group">
                  <label for="typeOfMail">Type of mail:</label>
                  <select class="form-select form-select-sm" id="typeOfMail">
                      <option>Letter</option>
                      <option selected>Reserved</option >
                      <option>Package</option>
                      <option>Fast delivery</option>
                      <option>Returned mail</option>
                  </select >
              </div>
              <div class="form-group">
                  <label for="destination">Destination:</label>
                  <select class="form-select form-select-sm" id="destination">
                      <option>Domestic</option>
                      <option>Foreign</option>
                  </select >
              </div>
          </form >
      </div>
      <div class="col-9 text-center">
          <h2>Picture</h2>
      </div>
  </div>
</main>

如果需要更精准控制下拉框的宽度,也可以给select添加固定宽度类,比如w-25(占父容器25%宽度),或者自定义内联样式style="width: 80px"都可以。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:24:08