CSS实现隐藏滚动条同时又可以滚动

7,149 阅读1分钟

移动端页面为了更接近原生的体验,是否可以隐藏滚动条,同时又保证页面可以滚动?

使用 overflow:hidden 隐藏滚动条,但存在的问题是:页面或元素失去了滚动的特性。
由于只需要兼容移动浏览器(Chrome 和 Safari),于是想到了自定义滚动条的伪对象选择器
::-webkit-scrollbar

 

关于这个选择器的介绍可以参考:
Styling Scrollbars
Custom Scrollbars in WebKit

 

应用如下 CSS 可以隐藏滚动条:

.element::-webkit-scrollbar {display:none}

如果要兼容 PC 其他浏览器(IE、Firefox 等),可以在容器外面再嵌套一层 overflow:hidden 内部内容再限制尺寸和外部嵌套层一样,就变相隐藏了。

<!DOCTYPE html>      
<html lang="en">      
<head>      
    <meta charset="UTF-8">      
    <title>CSS实现隐藏滚动条同时又可以滚动</title>    
    <style type="text/css">
      body{margin: 0;background: #ddd;}

      .header{width:100%;height: 100px;overflow-x:scroll;overflow-y:hidden;}
      .content{height: 100px;width: 5000px;background: linear-gradient(to right, green , blue);}
      .header::-webkit-scrollbar {display:none}

      .outer-container {width: 500px; height: 700px;position: relative;overflow: hidden;}
      .inner-container {height: 700px;position: absolute; left: 0;overflow-x: hidden;overflow-y: scroll;}
      .inner-container::-webkit-scrollbar {display: none;}
      .content2 {height: 5000px;width: 500px;background: linear-gradient(red , blue);}
    </style>     
</head>      
<body>
  <div class="header">
    <div class="content"></div>
  </div>

  <div class="outer-container">
    <div class="inner-container">
      <div class="content2"></div>
    </div>
  </div>
</body>      
</html> 


\

\

\

备注:欢迎加入web前端求职招聘qq群:668352707\