osition屬性規定元素的定位類型,即建立元素布局所用的定位機制。任何元素都可以定位,不過絕對位置或固定定位元素會產生一個塊級框,而不論該元素本身是什麼類型。相對定位元素會相對於它在正常流中的預設位置位移。
position屬性值除了預設的static外,還有relative、absolute、fixed,本文重點討論fixed屬性值。
一、position:fixed屬性的含義
fixed:產生絕對位置的元素,相對於瀏覽器視窗進行定位。元素的位置通過 "left", "top", "right" 以及 "bottom" 屬性進行規定。
我們平時所說的固定定位指的就是fixed,設定了固定定位的元素不會隨捲軸上下滾動。
二、一般的 position:fixed; 實現方法
#top{position:fixed;bottom:0;right:20px}實現了id為top的元素固定在瀏覽器的底部和距離右邊20個像素的位置
#top{position:fixed;top:20px;right:20px}實現了id為top的元素固定在距離瀏覽器的頂部20個像素和距離右邊20個像素的位置
三、IE6下position:fixed; 實現方法
在IE6中是不能直接使用 position:fixed; 。你需要一些 CSS Hack 來解決它
相同的還是讓 <div id="top">...</div> 元素固定在瀏覽器的底部和距離右邊的20個像素,這次的代碼是:
#top{position:fixed;bottom:0;right:20px;_position:absolute;_top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0)));}
right 跟 left 屬性可以用絕對位置的辦法解決,而 top 跟 bottom 就需要用上面的運算式來實現。其中在_position:absolute; 中的 _ 符號只有 IE6 才能識別,目的是為了區分其他瀏覽器
1、使元素固定在瀏覽器視窗的頂部:
#top{_position:absolute;_top:expression(eval(document.documentElement.scrollTop));}
2、使元素固定距瀏覽器視窗的頂部a像素的位置:
#top{_position:absolute;_top:expression(eval(document.documentElement.scrollTop));_margin-top:a;}
或者
#top{_position:absolute;_top:expression(eval(document.documentElement.scrollTop+a));}
3、使元素固定在瀏覽器視窗的底部:
#top{_position:absolute;_top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0)));}
4、使元素固定在距瀏覽器視窗的底部b像素的位置:
#top{_position:absolute;_top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0)));_margin-bottom:b;}
或者
#top{_position:absolute;_top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||b)-(parseInt(this.currentStyle.marginBottom,10)||b)));}