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

如何将两个价格盒子居中?附现有HTML/CSS代码求解决方案

解决两个价格盒子居中的问题

我来帮你搞定这个居中难题~原来的代码是为4个col-md-3的盒子设计的(4×3=12列,刚好填满Bootstrap的12列栅格),现在只剩两个的话,总宽度只有6列,加上父容器设置了float:left,自然就会靠左对齐。咱们可以通过调整CSS和小改HTML来实现居中:

方案1:用Flex布局快速实现(推荐)

修改后的HTML代码

<div id="fh5co-pricing-section"> 
  <div class="container"> 
    <div class="row"> 
      <div class="col-md-6 col-md-offset-3 text-center fh5co-heading animate-box"> 
        <h2>Pricing</h2> 
        <p>Lorum ipsum</p> 
      </div> 
    </div> 
    <div class="row"> 
      <div class="pricing"> 
        <div class="col-md-3 animate-box"> 
          <div class="price-box"> 
            <h2 class="pricing-plan">Caller</h2> 
            <div class="price"><sup class="currency">€</sup>2,50<small>/month</small></div> 
            <p>Lorum ipsum</p> 
            <a href="#" class="btn btn-select-plan btn-sm">Select Plan</a> 
          </div> 
        </div> 
        <div class="col-md-3 animate-box"> 
          <div class="price-box"> 
            <h2 class="pricing-plan">Watch</h2> 
            <div class="price"><sup class="currency">€</sup>11,50<small>/month</small></div> 
            <p>Lorum ipsum</p> 
            <a href="#" class="btn btn-select-plan btn-sm">Select Plan</a> 
          </div> 
        </div> 
      </div> 
    </div> 
  </div> 
</div>

修改后的CSS代码

#fh5co-pricing-section { 
  padding: 7em 0; 
  background: #fcfcfc; 
} 

@media screen and (max-width: 768px) { 
  #fh5co-pricing-section { 
    padding: 3em 0; 
  } 
} 

#fh5co-pricing-section .pricing { 
  display: flex; /* 改成flex布局 */
  justify-content: center; /* 水平居中 */
  margin-bottom: 30px; 
  width: 100%; /* 确保占满父容器宽度 */
} 

#fh5co-pricing-section .price-box { 
  text-align: center; 
  padding: 30px; 
  background: #fff; 
  margin-bottom: 40px; 
  position: relative; 
  -webkit-box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.11); 
  -moz-box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.11); 
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.11); 
  top: 2px; 
  -webkit-transition: 0.3s; 
  -o-transition: 0.3s; 
  transition: 0.3s; 
}

方案2:利用Bootstrap栅格偏移(传统方法)

如果不想用Flex,也可以调整列宽和偏移量,让两个盒子居中:

把每个价格盒子的col-md-3改成col-md-4 col-md-offset-1,这样每个盒子占4列,两边各留1列的空白(2×4 + 2×1=12列),自然就居中了:

<div class="col-md-4 col-md-offset-1 animate-box"> 
  <!-- 价格盒子内容 -->
</div>
<div class="col-md-4 animate-box"> 
  <!-- 价格盒子内容 -->
</div>

改动说明:

  1. 方案1中,我把.pricing的display:block和float:left改成了display:flex和justify-content:center,同时添加width:100%确保它占满父容器的宽度,这样里面的两个col-md-3盒子就会自动水平居中。
  2. 方案2是利用Bootstrap的栅格系统,调整列宽和偏移,让总列数刚好填满12列,实现居中效果。

两种方法都能解决你的问题,推荐方案1,因为Flex布局更灵活,后续如果增减盒子数量,调整起来更方便~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:41:35