如何在Bootstrap布局中实现仅表格可滚动、下方组件固定?
解决方案:实现可滚动表格+固定下方组件
要让表格区域垂直滚动,同时下方的优惠券组件保持固定,只需要调整容器的高度和滚动属性,具体步骤如下:
1. 修改自定义CSS类
将.wrapper的样式调整为:
.wrapper{ max-height: 400px; /* 按需设置最大高度,超过则触发滚动 */ width: 100%; /* 让容器占满父级宽度,消除右侧留白 */ overflow-y: auto; /* 垂直方向内容超出时显示滚动条 */ }
max-height:限制表格容器的最大高度,也可以根据需求改成固定高度(比如height: 350px)overflow-y: auto:当表格内容高度超过容器高度时,自动显示垂直滚动条width: 100%:替换原有的width: fit-content,让容器和父级vstack宽度匹配,避免不必要的留白
2. 保留原有Bootstrap布局优势
你当前的vstack垂直堆叠布局已经能满足需求,修改后表格所在的.wrapper会独立滚动,下方的优惠券组件会始终固定在容器底部,不会随表格滚动。
进阶:固定表头(可选)
如果需要滚动表格时表头保持固定不滚动,可以给表格表头添加额外样式:
.table thead th { position: sticky; top: 0; background-color: #fff; /* 设置和表格主体一致的背景色,避免被滚动内容覆盖 */ z-index: 1; }
这样滚动表格内容时,表头会固定在容器顶部,提升数据可读性。
修改后的完整代码示例
<div class="vstack gap-3"> <div class="wrapper"> <div class="order table-responsive rounded-1 border border-secondary-subtle"> <table class="table m-0"> <thead> <tr> <th colspan="2">Sản phẩm</th> <th>Giá</th> <th>Số lượng</th> <th>Tạm tính</th> </tr> </thead> <tbody> <!-- 可添加更多表格行测试滚动效果 --> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> </tr> </tbody> </table> </div> </div> <div class="rounded-1 border border-secondary-subtle"> <div class="hstack gap-3 px-1 d-flex justify-content-center"> <div class="pe-0 align-middle"> <label for="voucher" class="me-3 p-0 fw-bold fs-5 text-nowrap"> Mã giảm giá </label> </div> <div class="ps-0"> <div class="hstack border border-secondary-subtle rounded-pill mx-2"> <input type="text" class="inp" id="voucher" placeholder="Nhập voucher"> <button class="rounded-pill apply_btn">Áp dụng</button> </div> </div> </div> </div> </div>
内容的提问来源于stack exchange,提问作者Curt
相关产品推荐
相关产品推荐

