基于HTML和CSS实现半粘性表格:固定总计列,科目列可横向滚动的方案咨询
实现总计列粘性固定+科目列横向滚动的方案
你可以通过CSS的position: sticky属性轻松实现这个需求,核心思路是让总计(Total)所在的列固定在左侧区域,同时让科目列支持横向滚动。下面是具体的修改步骤:
1. 更新CSS样式
在你现有的CSS代码中添加/调整以下规则:
.last-workouts .last-workout-table { border-radius: 20px; /* 为sticky元素提供定位上下文 */ position: relative; /* 保留横向滚动功能 */ overflow-x: auto; } /* 可选:让左侧测试信息列(如TYT-1)也跟着固定 */ .last-workouts .test { position: sticky; left: 0; /* 设置背景色防止滚动时后面内容穿透 */ background-color: #00bad6; /* 提高层级确保在其他列上方 */ z-index: 2; } /* 核心:让总计列固定 */ .last-workouts .result { position: sticky; /* 因为.test宽度是20%,所以left设为20%,让总计列紧跟在测试列右侧 */ left: 20%; /* 必须设置背景色,避免滚动时显示后面的科目列内容 */ background-color: #F0F0F0; /* 层级低于测试列,高于科目列 */ z-index: 1; } /* 以下是你原有CSS样式,保留即可 */ .last-workouts table { border-collapse: collapse; border-spacing: 0; width: 100%; border: 1px solid #ddd; } .last-workouts table .tests:not(:last-child) { border-bottom: 1px solid #050a6c; } .last-workouts .test { text-align: center; color: #FFFFFF; padding: 1rem 0; width: 20%; } .last-workouts .test .number-test, .last-workouts .test .type-test { font-weight: bold; } .last-workouts .result { margin: 0; padding: 0; text-align: center; width: 12%; } .last-workouts .inner-table { border: none; } .last-workouts .inner-table tr:not(:last-child) { border-bottom: 1px solid #a9a9a9; } .last-workouts .total { color: #00bad6; font-weight: bold; padding: .25rem; } .last-workouts .inner-table .box td { padding: 0.5rem; border: 1px solid #a9a9a9; } .last-workouts .inner-table .box .bold { font-weight: bold; } .last-workouts .inner-table .box .bold.red { color: red; } .last-workouts .inner-table .box div { padding: .5rem; } .last-workouts .lessons { margin: 0; padding: 0; text-align: center; width: 12%; } .last-workouts .lessons:not(:last-child) { border-right: 2px solid #000000; }
2. HTML结构无需修改
你的现有HTML结构完全适配这个方案,不需要做任何调整。
效果说明
- 当页面横向滚动时,总计(Total)列会固定在左侧,不会跟随滚动。
- 数学、历史、生物等科目列会正常横向滚动,滚动时后续科目会自然移动到总计列的旁边,完全符合你的需求。
- 如果你不需要左侧的测试信息列固定,可以直接删除
.last-workouts .test的sticky相关样式,只保留总计列的固定逻辑即可。
内容的提问来源于stack exchange,提问作者magic bean
相关产品推荐
相关产品推荐

