如何将Bootstrap的col-10 div固定在右侧并实现内容滚动?
解决方法
针对你遇到的布局问题,结合Bootstrap 5的特性,调整方案如下:
核心调整思路
- 避开顶部导航栏:因为导航栏是
sticky-top固定在顶部,所以侧边栏和主内容区都需要留出顶部空间,避免被遮挡。 - 固定侧边栏并适配高度:让侧边栏从导航栏下方开始,高度占满剩余视口。
- 主内容区固定位置+滚动:利用Bootstrap的偏移类留出侧边栏宽度,同时设置高度和滚动属性,实现类似YouTube的内容滚动效果。
修改后的完整代码
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> <!-- 顶部导航栏 --> <nav class="navbar sticky-top navbar-expand-lg navbar-light" style="background-color: #025;"> <div class="container-fluid"> <a class="navbar-brand text-white" href="{% url 'users:home' %}" style="font-size: 25px; font-weight:600;"> <img src="{% static 'images/apple-icon.png' %}" class="d-inline-block align-text-center" style="margin-left: 50px; height: 40px;"> Digi Dash </a> <!-- 补全登录状态判断的逻辑 --> {% if user.is_authenticated %} <!-- 已登录用户的导航内容 --> {% else %} <div class="d-flex ms-auto"> <a class="nav-link" href="{% url 'users:login' %}"> <button type="button" class="btn btn-outline-primary text-white" style="border-radius: 10px;">Log In</button> </a> </div> {% endif %} </div> </nav> <!-- 侧边栏+主内容容器 --> <div class="container-fluid h-100"> <div class="row h-100"> <!-- 固定侧边栏 --> <div class="col-2" id="side-nav" style="position:fixed; top:56px; height: calc(100vh - 56px);"> <h4> <img src="{{ user.profile.profile_pic.url }}" alt="用户头像" style="max-width: 150px; max-height:150px; border-radius: 50%;"> <br> <span> Hi <strong style="color: #B9C04C; cursor:default;"> {{ user.username }}</strong></span> </h4> <!-- 侧边栏导航链接 --> <a class="d-block text-center side-link text-white mb-3" href="#"><iconify-icon icon="material-symbols:dashboard"></iconify-icon> DashBoard</a> <a class="d-block text-center side-link text-white mb-3" href="#">My Order</a> <a class="d-block text-center side-link text-white mb-3" href=""><iconify-icon icon="solar:moon-fog-bold"></iconify-icon> Dark Mode</a> <a class="d-block text-center side-link text-white mb-3" href="#">My Address</a> <hr> </div> <!-- 右侧可滚动主内容区 --> <div class="col-10 offset-2" style="margin-top:56px; height: calc(100vh - 56px); overflow-y:auto;"> <div class='col-sm-12' url-endpoint='{% url "users:api_data" %}'> <div class='col-sm-5 mb-3' style="float: left;"> <canvas id="myChart2" width="400" height="200"></canvas> </div> <div class='col-sm-5 mb-3' style="float: left;"> <canvas id="myChart" width="400" height="200"></canvas> </div> <div class='col-sm-5 mb-3' style="float: left;"> <canvas id="myChart3" width="400" height="200"></canvas> </div> </div> </div> </div> </div>
关键调整说明
- 侧边栏添加
top:56px和height: calc(100vh - 56px):让侧边栏从导航栏下方开始,高度占满剩余视口区域。 - 主内容区用
offset-2:自动适配侧边栏的宽度,无需手动计算margin;同时设置margin-top:56px避开顶部导航栏,height: calc(100vh - 56px)固定内容区高度,overflow-y:auto开启垂直滚动。 - 侧边栏链接用
d-block和mb-3类:替换原有的<br>标签,让布局更规范,间距更统一。
内容的提问来源于stack exchange,提问作者Shreyash mishra
相关产品推荐
相关产品推荐

