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

如何用Bootstrap实现多个figure元素的水平排列及垂直对齐?

解决Bootstrap中figure元素横向排列问题

问题回顾

之前用Bootstrap实现多张图片横向并排的代码如下:

<div class="container border rounded overflow">
    <div class="row text-center p-2 flex-nowrap" id="anID">
      
        <img src="../../static/img1.jpg" width=15% alt="">
      
    
        <img src="../../static/mg2.jpg" width=15% alt="">
     
...
    </div>
  </div>

实现效果为图片在圆角容器内横向并排。但将img替换为包含图片和标题的figure元素后,元素变成上下叠放,对应代码:

<div class="container border rounded">
    <div class="row text-center pt-2 px-2" id="anotherID">
      
        <figure>
          <img src="../../static/img2.jpg" width=15% alt="">
          <figcaption>a caption</figcaption>
        </figure>
      
        <figure>
          <img src="../../static/img3.jpg" width=15% alt="">
          <figcaption>another caption</figcaption>
        </figure>
      
        ...
    </div>
  </div>

解决方案

方法一:行内块级模式适配

给每个figure添加d-inline-block类,同时恢复row的flex-nowrap属性(与原图片布局保持一致):

<div class="container border rounded overflow">
    <div class="row text-center p-2 flex-nowrap" id="anotherID">
      
        <figure class="d-inline-block mb-0">
          <img src="../../static/img2.jpg" width=15% alt="">
          <figcaption>a caption</figcaption>
        </figure>
      
        <figure class="d-inline-block mb-0">
          <img src="../../static/img3.jpg" width=15% alt="">
          <figcaption>another caption</figcaption>
        </figure>
      
        ...
    </div>
  </div>
  • d-inline-block:将figure从默认块级元素改为行内块级,使其可在同一行排列
  • mb-0:消除figure默认下边距,避免不必要的间距
  • flex-nowrap:防止内容换行,维持横向排列效果

方法二:Flex布局特性利用

借助Bootstrap的flex工具类,让figure作为flex item实现横向排列:

<div class="container border rounded overflow">
    <div class="row text-center p-2 flex-nowrap align-items-center" id="anotherID">
      
        <figure class="flex-shrink-0 mx-2">
          <img src="../../static/img2.jpg" width=15% alt="">
          <figcaption>a caption</figcaption>
        </figure>
      
        <figure class="flex-shrink-0 mx-2">
          <img src="../../static/img3.jpg" width=15% alt="">
          <figcaption>another caption</figcaption>
        </figure>
      
        ...
    </div>
  </div>
  • flex-shrink-0:避免figure在flex容器中被压缩,保持原有宽度
  • mx-2:给figure添加横向间距,优化布局美观度
  • align-items-center:让所有figure垂直居中对齐,匹配最初的布局需求

原因说明

img属于行内替换元素,默认不会独占一行,因此能自然横向排列;而figure是块级元素,默认会占满父容器宽度,导致上下叠放。通过修改display属性或利用flex布局特性,即可让figure实现与img一致的横向排列效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:21:29