Skip to content

Instantly share code, notes, and snippets.

@simonid
Created February 23, 2018 02:12
Show Gist options
  • Save simonid/ec4f467705d75f310754cb87a62e5b97 to your computer and use it in GitHub Desktop.
Save simonid/ec4f467705d75f310754cb87a62e5b97 to your computer and use it in GitHub Desktop.
前端随笔

隐藏滚动条

方法1

html{
    overflow-y : scroll;
}

这段样式可以强制显示IE的垂直滚动条,但是忽略了水平滚动条
但是,即使页面中不需要垂直滚动条时,也会出现垂直滚动条

方法2

html{
    overflow-x : hidden;
    overflow-y : auto;
}

隐藏了横向滚动条,垂直滚动条自适应,在不必要时隐藏
缺陷是页面需要横向滚动条时,屏幕外的内容会因为无法水平滚动而被遮挡

方法3

body{
    margin-right : -15px;
    margin-bottom : -15px;
}

人为地在水平和垂直方向增加一个负值,垂直滚动根据内容自适应显示
缺陷是,人为增加的margin无法填充内容

如何隐藏滚动条并且还能滚动页面

针对webkit内核

webkit内核的浏览器中,可以加入以下样式,隐藏滚动条,并且使得页面可以滚动:

::-webkit-scrollbar{
  display:none;
}

针对其他浏览器

在其他浏览器中,可以设置父容器宽度100%,子容器宽度为100%+18px

还有另外一个思路:
大致方法是在父容器内套一个内容子容器,然后父容器设置overflow:hidden,子容器设置overflow-y:scroll;overflow-x:hidden;,并且父容器的width小于子容器的width

demo:

<style>
    .nav_wrap{  
    height: 400px;  
    width: 200px;  
    overflow: hidden;  
    border: 1px solid #ccc;  
    margin: 20px auto;  
}  
.nav_ul{  
    height: 100%;  
    width: 220px;  
    overflow-y: auto;  
    overflow-x: hidden;  
}  
.nav_li{  
    border: 1px solid #ccc;  
    margin: -1px;  
    height: 40px;  
    line-height: 40px;  
    text-align: center;  
    font-size: 12px;  
    width: 200px;  
}  
.btn_wrap{  
    text-align: center;  
}  
</style>
<body>
    <div class= "nav_wrap">  
        <ul class= "nav_ul">        
            <li class="nav_li">我是菜单1</li>  
            <li class="nav_li">我是菜单2</li>  
        </ul>  
    </div>  
</body>

上述方法参考自:
[CSDN - 纯css,div隐藏滚动条,保留鼠标滚动效果。](http://blog.csdn.net/liusaint1992/article/details/51277751)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment