2011-08-26 46 views
1

我想創建一個固定的div,這樣即使向下滾動頁面,div仍然保留在頁面的中心。但是我有一個問題,即使向下滾動頁面,div的某些部分仍然隱藏。請參閱此jsfiddle demo以查看代碼和問題。如果頁面滾動,CSS浮動:

HTML:

<div class="wrap"> 
    <div class="main">Normal div </div> 
    <div class="box">This should be in the slide down if page is scrolled down.</div> 
</div> 

CSS:

.wrap{ 
    border: 1px solid green; 
    width:500px; 
    overflow:auto; 
    margin:0 auto; 
} 

.main{ 
    border:1px solid blue; 
    width:400px; 
    float:right; 
} 

.box{ 
    border:1px solid red; 
    width:85px; 
    top:200px; 
    position: fixed; 
} 

回答

3

當一個元素絕對定位或固定的,你可以使用topbottom CSS屬性迫使元素來填充完全屏幕的高度:

.box{ 
border:1px solid red; 
position: fixed; 
width:85px; 
bottom:0px; 
top:0px; 
overflow-x: hidden; 
overflow-y: auto 
} 

或者是垂直在屏幕上居中:

.box{ 
border: 1px solid red; 
position: fixed; 
width:85px; 
bottom: 20%; 
top: 20%; 
overflow-x: hidden; 
overflow-y: auto 
} 

規則overflow-y: auto確保如果需要一個垂直滾動條將出現,而規則overflow-x: hidden;是爲了防止水平scroolbar出現。

0

這是固定位置的行爲,如果你不知道的固定<div>的高度,你不能垂直居中只有CSS。 但是,您可以使用一些JavaScript技巧來修改側邊欄,使屏幕分辨率如here

3

如果你不想經歷JavaScript的痛苦,只需設置top,heightoverflow屬性爲.box。你的問題是你沒有設置heightoverflow。例如:

.box{ 
    border:1px solid red; 
    width:85px; 
    top:200px; 
    position: fixed; 
    height: 200px; 
    overflow: scroll; /* or hidden */ 
} 
1

使用下面的JavaScript來中心,您的div屏幕上

<script type="text/javascript"> 
    function getwidth() {  
     if (typeof (window.innerWidth) == 'number') 
      return window.innerWidth; 
     else if (document.documentElement && document.documentElement.clientWidth) //IE 6+ 
      return document.documentElement.clientWidth;   
     return 0; 
    }; 

    function getheight() {  
     if (typeof (window.innerHeight) == 'number') 
      return window.innerHeight; 
     else if (document.documentElement && document.documentElement.clientHeight) //IE 6+ 
      return document.documentElement.clientHeight;  
     return 0; 
    }; 

    function getscroll() {  
     if (self.pageYOffset)  
      return self.pageYOffset; 
     else if (document.documentElement && document.documentElement.scrollTop) 
      return document.documentElement.scrollTop; 
     else if (document.body)  
      return document.body.scrollTop;  
     return 0; 
    }; 

    function show(mydivW, mydivH) { 
     var w = getwidth()/2 - mydivW/2; 
     var h = getheight()/2 - mydivH/2 + getscroll(); 
     var box = document.getElementById('mydiv'); 
     box.style.top = h + 'px'; 
     box.style.left = w + 'px'; 
     box.style.display = 'block'; 
    }; 
</script>