CSS:position:fixed使用(轉)


 

position屬性規定元素的定位類型,即建立元素布局所用的定位機制。任何元素都可以定位,不過絕對定位或固定定位元素會生成一個塊級框,而不論該元素本身是什么類型。相對定位元素會相對於它在正常流中的默認位置偏移。
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)));

}

四、IE6下的閃動問題

問題還沒有完全解決。在用了上面的辦法后,你會發現:被固定定位的元素在滾動滾動條的時候會閃動。解決閃動問題的辦法是在 CSS 文件中加入:

*html{background-image:url(about:blank);background-attachment:fixed;}

其中 * html選擇器hack是給 IE6 識別的。

到此,IE6 的 position:fixed; 問題已經被解決了

原文:http://blog.sina.com.cn/s/blog_51048da701018jzw.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM