2008-10-07 02:03

CSS fixed 定位( FF / IE6 )

fixed 定位主要是以 window 物件區塊做定位依據,所以不會隨頁面捲動而變動定位。

以往要達成這種模式的定位都要利用 JavaScript 的 onscroll 事件去達成,是蠻吃重的一種方法,而且流暢度也不好,會有閃爍的現象。

利用 fixed 定位可以簡化 JavaScript 的開發和負擔,而且又穩定且簡單設定。

  1. body{ 
  2.    height:1200px; 
  3.  
  4.    /* prevent screen flash in IE6(解決 IE6 不正常閃爍) */ 
  5.    background:url(nothing.txt) white fixed; 
  6. } 
  7.  
  8. div{ 
  9.    background:#FF0066; 
  10.    border:4px solid #FF9999; 
  11. } 
  12.  
  13. /* 水平置中 */ 
  14. .fixed-center{ 
  15.    width:100px; 
  16.    height:100px; 
  17.    position:fixed; 
  18.    top:50%; 
  19.    left:50%; 
  20.  
  21.    /* 上邊界計算 */ 
  22.    /* -(border-top-width + padding-top + (height/2) ) */ 
  23.    /* 或者是整體高除以二(offsetHeight/2) */ 
  24.    margin-top:-52px; 
  25.  
  26.    /* 左邊界計算 */ 
  27.    /* -(border-left-width + padding-left + (width/2) ) */ 
  28.    /* 或者是整體寬除以二(offsetWidth/2) */ 
  29.    margin-left:-52px; 
  30.  
  31.    /* position fixed for IE6 */ 
  32.    _position: absolute; 
  33.    _margin-top:0; 
  34.  
  35.    /* clientHeight:不包含邊匡的區塊高度( padding + height ) */ 
  36.    /* offsetHeight:包含邊匡的區塊高度( border + padding + height ) */ 
  37.    _top:expression(documentElement.scrollTop + ( documentElement.clientHeight-this.offsetHeight )/2 
  38.    ); 
  39. } 
  40.  
  41. .fixed-top-center{ 
  42.    width:100px; 
  43.    height:100px; 
  44.    position:fixed; 
  45.    top:0; 
  46.    left:50%; 
  47.    margin-left:-52px; 
  48.  
  49.    /* position fixed for IE6 */ 
  50.    _position: absolute; 
  51.    _top:expression(documentElement.scrollTop); 
  52. } 
  53.  
  54. .fixed-bottom-center{ 
  55.    width:100px; 
  56.    height:100px; 
  57.    position:fixed; 
  58.  
  59.    bottom:0; 
  60.    left:50%; 
  61.    margin-left:-52px; 
  62.  
  63.    /* position fixed for IE6 */ 
  64.    _position: absolute; 
  65.    _top:expression( documentElement.scrollTop+documentElement.clientHeight-this.offsetHeight ); 
  66. } 


展示頁面(Demo Page)

參考來源:上下左右置中、不隨頁面捲動的內容-小正正教室

4 回應:

匿名 提到...

您好! 請問一下~
在.fixed-top-center{}中
若是設"top: 20px",它好像還是置頂?!
有什麼方法可以解決呢?
謝謝~

匿名 提到...

不好意思 上一則留言沒有寫清楚
我的問題是指在ie6的狀態下。
謝謝~

Jax Hu 提到...

IE6 的設定方式
_top:expression(documentElement.scrollTop+20);

Jax Hu 提到...

補充一下,所有底線(_)開頭的樣式都是給IE6看的