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

如何将侧边栏中的滚动条移至侧边栏右边缘?

问题:侧边栏滚动条需紧贴右边缘

我正在为SPA项目定制后台管理面板,侧边栏代码如下:

HTML代码

<div class="sidebar">
    <div class="logo_content">
        <div class="logo">
            <i class='bx bxl-c-plus-plus'></i>
            <div class="logo_name">CodeX</div>
        </div>
        <i class='bx bx-menu' id="btn"></i>
    </div>
    <div class="items-list">
        <ul class="nav-list">
            <li>
                <a href="#">
                    <i class='bx bxs-grid-alt'></i>
                    <span class="links_name">Dashboard</span>
                </a>
            </li>
        </ul>
        <ul class="nav-list">
            <li>
                <a href="#">
                    <i class='bx bxs-user'></i>
                    <span class="links_name">User</span>
                </a>
            </li>
        </ul>
        .
        .
        <!-- uls come here -->
        .
        .
        .
    </div>
</div>

CSS代码

.sidebar .items-list{
    height: calc(100% - 130px);
    overflow-y: scroll;
    overflow-x: hidden;
}
.sidebar ul{
    margin-top: 20px;
}

.sidebar ul li{
    position: relative;
    height: 50px;
    width: 100%;
    margin: 0 5px;
    list-style: none;
    line-height: 50px;
}

.sidebar ul li a{
    color: #fff;
    display: flex;
    align-items: center;
    text-decoration: none;
    border-radius: 12px;
    transition: all .4s ease;
}

.sidebar ul li a:hover{
    color: #11101d;
    background: #fff;
}

.sidebar ul li a i{
    height: 50px;
    min-width: 50px;
    border-radius: 12px;
    line-height: 50px;
    text-align: center;
    font-size: 30px;
}

当前页面效果:
最终效果

目前侧边栏的滚动条与侧边栏右边缘存在间隙,希望将滚动条紧贴右边缘,请问该如何操作?


解决方案

要让滚动条紧贴侧边栏右边缘,可从以下两方面调整:

1. 移除容器及列表项的右侧间距

当前.sidebar ul li设置的margin: 0 5px会让列表整体左移,间接造成滚动条与边缘的间隙,同时清理.items-list的默认右侧内边距/外边距:

.sidebar .items-list{
    height: calc(100% - 130px);
    overflow-y: scroll;
    overflow-x: hidden;
    padding-right: 0; /* 清除默认右侧内边距 */
    margin-right: 0;  /* 清除默认右侧外边距 */
}

.sidebar ul li{
    position: relative;
    height: 50px;
    width: 100%;
    margin: 0 0 0 5px; /* 仅保留左侧margin,移除右侧margin */
    list-style: none;
    line-height: 50px;
}

2. 自定义滚动条样式(可选,优化视觉贴合度)

若调整后仍有间隙,可通过自定义滚动条样式让其完全贴合边缘:

/* 自定义滚动条轨道 */
.sidebar .items-list::-webkit-scrollbar-track {
    background: transparent;
}

/* 自定义滚动条宽度 */
.sidebar .items-list::-webkit-scrollbar {
    width: 6px;
}

/* 自定义滚动条滑块 */
.sidebar .items-list::-webkit-scrollbar-thumb {
    background-color: rgba(255,255,255,0.3);
    border-radius: 3px;
}

调整后滚动条即可紧贴侧边栏右边缘,同时保留原有布局的视觉效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:54:23