3種方法實現CSS隱藏滾動條並能夠滾動內容

原文連接:http://caibaojian.com/hide-scrollbar.htmlcss

隱藏滾動條的同時還須要支持滾動,咱們常常在前端開發中遇到這種狀況,最容易想到的是加一個iscroll插件,但其實如今CSS也能夠實現這個功能,我已經在不少地方使用了,下面一塊兒看看這三種方法。html

方法1:計算滾動條寬度並隱藏起來

在本站的側欄,你能夠看到前端日報的那塊內容並無滾動條,但鼠標移上去卻能夠滾動內容。這是什麼技術呢? 其實我只是把滾動條經過定位把它隱藏了起來。前端

演示css3

下面給一個簡化版的代碼·web

<div class="outer-container">
    <div class="inner-container">
    	......
    </div>
</div>
.outer-container{
	width: 360px;
	height: 200px;
	position: relative;
	overflow: hidden;
}
.inner-container{
	position: absolute;
	left: 0;
	top: 0;
	right: -17px;
	bottom: 0;
	overflow-x: hidden;
	overflow-y: scroll;
}

演示chrome

這個代碼巧妙的向右移動了17個像素,恰好等於滾動條的寬度。這個值是我手動調試得來的。在chrome和IE沒發現問題。ide

方法2:使用三個容器包圍起來,不須要計算滾動條的寬度

該代碼最先是在Microsoft博客上看到的,跟我上面的思路差很少,只不過人家裏面又加多了一個盒子,將內容限制在盒子裏面了。這樣子就看不到滾動條同時也能夠滾動。url

代碼以下:spa

<div class="outer-container">
     <div class="inner-container">
        <div class="content">
            ......
        </div>
     </div>
 </div>
//code from http://caibaojian.com/hide-scrollbar.html
.element, .outer-container {
  width: 200px;
  height: 200px;
}

.outer-container {
  border: 5px solid purple;
  position: relative;
  overflow: hidden;
}

.inner-container {
  position: absolute;
  left: 0;
  overflow-x: hidden;
  overflow-y: scroll;
}

.inner-container::-webkit-scrollbar {
  display: none;
}

演示firefox

方法3:css隱藏滾動條

同時該文章還分享了一種經過CSS隱藏滾動條的方法,不過這個方法不兼容IE,作移動端的可使用。

那就是自定義滾動條的僞對象選擇器::-webkit-scrollbar,詳情請看以前的文章:CSS3自定義webkit滾動條樣式

chrome 和Safari

.element::-webkit-scrollbar { width: 0 !important }

IE 10+

.element { -ms-overflow-style: none; }

Firefox

.element { overflow: -moz-scrollbars-none; }


來源:前端開發博客

相關文章
相關標籤/搜索