css之隐藏滚动条

2,051 阅读1分钟

css之隐藏滚动条

隐藏滚动条的同时还需要支持滚动,我们经常在前端开发中遇到这种情况,最容易想到的是加一个iscroll插件,但其实现在CSS也可以实现这个功能,下面我们来看一下使用css隐藏滚动条的方法。

可以使用自定义滚动条的伪对象选择器::-webkit-scrollbar设置隐藏滚动条。

<html>
  <head>
    <style type="text/css">
      .img {
        height: 512px;
        background: url(../assets/yay.jpg) no-repeat center 0;
        background-size: 512px 512px;
      }
    </style>
  </head>
  
  <body>
    <div class="img" />
    <div class="img" />
  </body>
</html>

yay

<html>
  <head>
    <style type="text/css">
      .layout {
        height: 100vh;
        overflow-y: scroll;
      }

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

      .img {
        height: 512px;
        background: url(../assets/yay.jpg) no-repeat center 0;
        background-size: 512px 512px;
      }
    </style>
  </head>
  
  <body>
    <div class="layout">
      <div class="img" />
      <div class="img" />
    </div>
  </body>
</html>

yay

兼容各个浏览器

<html>
  <head>
    <style type="text/css">
      .layout::-webkit-scrollbar {
        display: none; /* Chrome Safari */
      }

      .layout {
        height: 100vh;
        scrollbar-width: none; /* firefox */
        -ms-overflow-style: none; /* IE 10+ */
        overflow-x: hidden;
        overflow-y: auto;
      }

      .img {
        height: 512px;
        background: url(../assets/yay.jpg) no-repeat center 0;
        background-size: 512px 512px;
      }
    </style>
  </head>
  
  <body>
    <div class="layout">
      <div class="img" />
      <div class="img" />
    </div>
  </body>
</html>

更精细控制。

/* 滚动条整体部分 */
html::-webkit-scrollbar {
  width: 0;
  height: 0;
}

/* 滚动条的轨道 */
html::-webkit-scrollbar-track {
  background: #f0f2f5;
  border-radius: 2px;
}

/* 滚动条里面的小方块 */
html::-webkit-scrollbar-thumb {
  background: #333333;
  border-radius: 10px;
}

html::-webkit-scrollbar-thumb:hover {
  background: #222222;
}

最后

以上就是css怎么隐藏滚动条方法,欢迎技术交流。你们的支持是我的动力~