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

如何在Bootstrap中让卡片从左到右排列?当前为上下排列

Bootstrap卡片横向排列解决方案

核心原因

卡片默认是块级元素,会独占一行,所以需要借助Bootstrap的布局工具类来实现横向排列,下面提供两种常用方案:


方案1:使用Bootstrap网格系统(推荐,自带响应式适配)

将所有卡片包裹在.row容器中,给每个卡片添加.col-*类分配宽度,既能实现横向排列,还能自动适配不同屏幕尺寸。

修改后的代码示例:

<div class="row g-3">
  <div class="col-md-3">
    <div class="card h-100">
      <img src="..." class="card-img-top" alt="..." />
      <div class="card-body text-center">
        <h5 class="card-title">Card title</h5>
        <p class="card-text">
          Some quick example text to build on the card title and make up the
          bulk of the card's content.
        </p>
        <a href="#" class="btn btn-primary">Go somewhere</a>
      </div>
    </div>
  </div>

  <div class="col-md-3">
    <div class="card h-100">
      <div class="card-body text-center">
        <h5 class="card-title">Card title</h5>
        <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
        <p class="card-text">
          Some quick example text to build on the card title and make up the
          bulk of the card's content.
        </p>
        <a href="#" class="card-link">Card link</a>
        <a href="#" class="card-link">Another link</a>
      </div>
    </div>
  </div>

  <!-- 剩余两张卡片同理,嵌套在col-md-3容器中 -->
  <div class="col-md-3">
    <div class="card h-100">
      <!-- 卡片内容 -->
    </div>
  </div>

  <div class="col-md-3">
    <div class="card h-100">
      <!-- 卡片内容 -->
    </div>
  </div>
</div>
  • .row:Bootstrap网格的行容器,用于包裹列元素
  • .col-md-3:中等屏幕(≥768px)及以上,每个卡片占1/4宽度;小屏幕下自动堆叠为垂直排列
  • .g-3:设置卡片间的间距
  • .h-100:让所有卡片高度统一,视觉更整齐
  • .text-center:替代废弃的<center>标签,实现内容居中

方案2:使用Flex布局工具类

如果不需要响应式堆叠,或者想快速实现横向排列,可直接用Bootstrap的Flex工具类:

<div class="d-flex flex-wrap gap-3">
  <div class="card" style="width: 16.5rem">
    <!-- 卡片内容 -->
  </div>
  <div class="card" style="width: 16.5rem">
    <!-- 卡片内容 -->
  </div>
  <!-- 剩余卡片 -->
</div>
  • .d-flex:将容器设为Flex布局,内部元素横向排列
  • .flex-wrap:容器宽度不足时,卡片自动换行
  • .gap-3:设置卡片间的间距

新手建议

  1. 避免使用废弃的<center>标签,改用Bootstrap提供的.text-center、.justify-content-center等工具类
  2. 尽量减少内联样式(如style="width: 16.5rem"),优先用网格类或宽度工具类(如.w-25)控制尺寸,更符合框架规范
  3. 熟悉Bootstrap的12列网格系统,这是布局核心,能轻松实现各类响应式效果
  4. 官方文档是最靠谱的学习资源,遇到布局问题可优先查阅布局相关章节

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:00:50