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

Bootstrap响应式布局小屏幕下将右侧边栏移至主内容上方的实现问题

解决方案

你要实现小屏侧边栏在上、大屏侧边栏在右的效果,直接用Bootstrap 5自带的响应式排序类就能实现,不需要自定义CSS:

  1. 利用带响应式前缀的order-*类,分别给主内容、侧边栏设置不同屏幕下的排序优先级
  2. 要实现小屏侧边栏的样式转换,搭配flex-*响应式类就能调整列表布局

修改后完整代码

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<main role="main">
    <div class="container">
        <div class="row">
            <!-- 主内容:默认排序2(小屏在下),md及以上排序1(在左) -->
            <div class="col-sm-12 col-md-8 order-2 order-md-1">
                this is the main content. this is the main content.this is the main content. <br />
                this is the main content. this is the main content.this is the main content. <br />
                this is the main content. this is the main content.this is the main content. <br />
                this is the main content. this is the main content.this is the main content. <br />
                this is the main content. this is the main content.this is the main content. <br />
                this is the main content. this is the main content.this is the main content. <br />
                this is the main content. this is the main content.this is the main content. <br />
            </div>
            <!-- 侧边栏:默认排序1(小屏在上),md及以上排序2(在右) -->
            <div class="col-sm-12 col-md-4 order-1 order-md-2">
                <h3>Sidebar</h3>
                <!-- 加flex响应式类实现样式转换:小屏横向排列,大屏纵向 -->
                <ul class="list-group flex-row flex-md-column flex-wrap">
                    <li class="list-group-item flex-fill"><a href="#">Sidebar Link 1</a></li>
                    <li class="list-group-item flex-fill"><a href="#">Sidebar Link 2</a></li>
                    <li class="list-group-item flex-fill"><a href="#">Sidebar Link 3</a></li>
                    <li class="list-group-item flex-fill"><a href="#">Sidebar Link 4</a></li>
                    <li class="list-group-item flex-fill"><a href="#">Sidebar Link 5</a></li>
                </ul>
            </div>
        </div>
    </div>
</main>

改动说明

  • 去掉了row上多余的d-flex类,Bootstrap的row本身就是flex布局容器,不需要额外添加
  • 主内容新增order-2 order-md-1:<768px屏幕下排序优先级为2,排在侧边栏后面;≥768px屏幕下排序优先级为1,排在侧边栏前面
  • 侧边栏新增order-1 order-md-2:<768px屏幕下排序优先级为1,排在主内容前面;≥768px屏幕下排序优先级为2,排在主内容后面
  • 侧边栏列表新增flex-row flex-md-column flex-wrap,配合flex-fill类实现小屏横向平铺、大屏纵向排列的样式转换效果,你也可以根据自己的需求调整其他响应式样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 08:12:03