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

如何让position: fixed的sidebar支持滚动查看全部项?

实现类似Twitter右侧栏的滚动效果

要实现你想要的效果,仅通过CSS调整即可完成,无需JavaScript。核心是用position: sticky替代fixed,并为侧边栏内容容器添加滚动属性,让侧边栏在页面滚动时保持在视口内,同时允许内部内容滚动查看全部项。

修改后的CSS代码如下:

body {
background: black;
color:white;
margin: 0; /* 移除默认边距避免布局偏移 */
}

.sidebar {
    position: sticky; /* 替换fixed为sticky */
    top: 0;
    width: 200px;
    max-height: 100vh; /* 限制侧边栏高度为视口高度 */
    background: darkred;
}

.sidebar-item-list {
    overflow-y: auto; /* 内容超出时显示滚动条 */
    max-height: 100vh; /* 内容容器高度匹配视口 */
}

.sidebar-item {
    padding: 50px 20px;
    font-size: 20px;
}

.sidebar-item:hover {
    background-color: rgba(0, 0, 0, 0.3);
}

.content {
    width: 500px;
    margin-left: 200px;
    border-left: 1px solid rgb(56, 68, 77);
    border-right: 1px solid rgb(56, 68, 77);
    background:blue;
}

.article {
    padding: 20px;
    margin-bottom: 20px;
}

效果说明:

  • 侧边栏会固定在视口顶部,随页面滚动始终保持可见
  • 当侧边栏内容高度超过视口高度时,内部自动出现滚动条,可滚动查看所有选项直到最后一项可见
  • 整体布局与原设计一致,同时实现了类似Twitter右侧栏的交互体验

HTML结构无需修改,保持你提供的原代码即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:05:17