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

如何用Bootstrap Grid实现两个Accordion手风琴并排布局?

用Bootstrap Grid实现并排手风琴完全可行!

当然可以借助Bootstrap的栅格系统轻松实现两个手风琴并排展示,这是Bootstrap布局能力的典型应用场景之一。核心思路就是利用栅格的列布局,把两个手风琴分别放在独立的栅格列中,让它们自动平分(或按你需要的比例占据)容器宽度。

下面是结合你提供的代码片段完善后的完整实现示例:

<!DOCTYPE html>
<html>
<head>
  <!-- 引入Bootstrap CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <style>
    img { 
      max-width: 100%; 
      max-height: 100%; 
    } 
    .accordion { 
      background-color: #eee; 
      color: #444; 
      cursor: pointer; 
      padding: 18px; 
      width: 100%; 
      border: none; 
      text-align: left; 
      outline: none; 
      font-size: 15px;
      transition: 0.4s;
    }
    .accordion.active, .accordion:hover {
      background-color: #ccc;
    }
    .panel {
      padding: 0 18px;
      background-color: white;
      max-height: 0;
      overflow: hidden;
      transition: max-height 0.2s ease-out;
    }
  </style>
</head>
<body>
  <div class="container mt-4">
    <div class="row">
      <!-- 第一个手风琴:占据6列(中等屏幕及以上) -->
      <div class="col-md-6 mb-3 mb-md-0">
        <button class="accordion">第一个手风琴标题1</button>
        <div class="panel">
          <p>这里是第一个手风琴的内容区域,可以放文字、图片或者其他元素。</p>
          <img src="your-image-url.jpg" alt="示例图片">
        </div>
        
        <button class="accordion">第一个手风琴标题2</button>
        <div class="panel">
          <p>更多内容示例...</p>
        </div>
      </div>

      <!-- 第二个手风琴:占据6列(中等屏幕及以上) -->
      <div class="col-md-6">
        <button class="accordion">第二个手风琴标题1</button>
        <div class="panel">
          <p>这是第二个手风琴的内容,和左边的手风琴完全独立工作。</p>
        </div>
        
        <button class="accordion">第二个手风琴标题2</button>
        <div class="panel">
          <p>另一部分内容,支持展开收起。</p>
        </div>
      </div>
    </div>
  </div>

  <!-- 控制手风琴展开收起的JS -->
  <script>
    var acc = document.getElementsByClassName("accordion");
    var i;

    for (i = 0; i < acc.length; i++) {
      acc[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight) {
          panel.style.maxHeight = null;
        } else {
          panel.style.maxHeight = panel.scrollHeight + "px";
        }
      });
    }
  </script>
</body>
</html>

关键要点说明:

  • 栅格布局:用row包裹两个col-md-6列,意味着在中等屏幕(≥768px)上两个手风琴各占一半宽度;在小屏幕上会自动堆叠成垂直排列,适配移动端。如果你想让小屏幕也保持并排,可以换成col-sm-6或者col-6。
  • 手风琴宽度:你的.accordion类已经设置了width: 100%,这很关键,能让手风琴自动填满所在栅格列的宽度,避免出现布局错位。
  • 样式兼容:保留了你提供的基础样式,补充了手风琴激活和悬停状态的样式,以及面板展开收起的过渡效果,让交互更流畅。

如果你的手风琴需要用Bootstrap官方的组件(而不是自定义的),只需要把自定义的手风琴结构换成Bootstrap的accordion组件,然后放在栅格列中即可,逻辑是完全一致的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:39:27