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

如何让15个分3行5列的按钮均匀分布并占满父容器?

最佳实现方案

方案一:Bootstrap网格系统适配(Bootstrap 4/5)

既然你已经在用Bootstrap,直接用它的原生网格布局就能解决问题,无需额外复杂调整:

  1. 父容器用container或container-fluid(需占满视口宽度时选后者),内部嵌套row并添加g-0类消除网格默认间距,保证按钮完全贴合父容器。
  2. 每个按钮外层套col类,15个按钮会自动按5列/3行排列,col会均分每行宽度。
  3. 给按钮加w-100 h-100类让其占满所在网格单元,再用d-flex align-items-center justify-content-center实现按钮文字居中。

示例代码:

<div class="container" style="height: 400px; border: 1px solid #ccc;">
  <div class="row g-0">
    <div class="col">
      <button class="btn btn-primary w-100 h-100 d-flex align-items-center justify-content-center">按钮1</button>
    </div>
    <div class="col">
      <button class="btn btn-primary w-100 h-100 d-flex align-items-center justify-content-center">按钮2</button>
    </div>
    <!-- 重复以上结构至15个按钮 -->
  </div>
</div>
  • 父容器的固定高度仅为演示用,实际可按需调整或由内容撑开。
  • g-0移除列间默认 gutter,确保按钮完全占满父容器宽度。

方案二:原生CSS Grid布局(无框架依赖)

如果不想依赖Bootstrap,用原生Grid布局更直接简洁:

  1. 父容器设置display: grid,通过grid-template-columns: repeat(5, 1fr)定义5列均分宽度,grid-template-rows: repeat(3, 1fr)定义3行均分高度。
  2. 清除按钮默认内外边距,设置width: 100%; height: 100%;让按钮填满网格单元。

示例代码:

<style>
  .button-container {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    grid-template-rows: repeat(3, 1fr);
    gap: 0; /* 需按钮间留间距时,可设具体数值如2px */
    height: 400px;
    border: 1px solid #ccc;
  }
  .button-container button {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    border: 1px solid #007bff;
    background-color: #007bff;
    color: #fff;
    cursor: pointer;
  }
</style>

<div class="button-container">
  <button>按钮1</button>
  <button>按钮2</button>
  <!-- 重复至15个按钮 -->
</div>
  • 1fr是网格弹性单位,会自动均分容器可用空间。

方案三:原生CSS Flex布局(兼容旧浏览器)

需兼容老浏览器时,Flex布局是可靠选择:

  1. 父容器设置display: flex; flex-wrap: wrap;,让按钮自动换行。
  2. 按钮设置flex: 1 0 20%;(5列对应每列基础宽度20%),height: calc(100% / 3);(3行对应每行高度为父容器1/3)。
  3. 清除按钮默认内外边距避免布局错位。

示例代码:

<style>
  .button-container {
    display: flex;
    flex-wrap: wrap;
    height: 400px;
    border: 1px solid #ccc;
    margin: 0;
    padding: 0;
  }
  .button-container button {
    flex: 1 0 20%;
    height: calc(100% / 3);
    margin: 0;
    padding: 0;
    border: 1px solid #007bff;
    background-color: #007bff;
    color: #fff;
    cursor: pointer;
  }
</style>

<div class="button-container">
  <button>按钮1</button>
  <button>按钮2</button>
  <!-- 重复至15个按钮 -->
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:25:26