2011-08-26 48 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>