fixed 定位主要是以 window 物件區塊做定位依據,所以不會隨頁面捲動而變動定位。
以往要達成這種模式的定位都要利用 JavaScript 的 onscroll 事件去達成,是蠻吃重的一種方法,而且流暢度也不好,會有閃爍的現象。
利用 fixed 定位可以簡化 JavaScript 的開發和負擔,而且又穩定且簡單設定。
body{
height:1200px;
/* prevent screen flash in IE6(解決 IE6 不正常閃爍) */
background:url(nothing.txt) white fixed;
}
div{
background:#FF0066;
border:4px solid #FF9999;
}
/* 水平置中 */
.fixed-center{
width:100px;
height:100px;
position:fixed;
top:50%;
left:50%;
/* 上邊界計算 */
/* -(border-top-width + padding-top + (height/2) ) */
/* 或者是整體高除以二(offsetHeight/2) */
margin-top:-52px;
/* 左邊界計算 */
/* -(border-left-width + padding-left + (width/2) ) */
/* 或者是整體寬除以二(offsetWidth/2) */
margin-left:-52px;
/* position fixed for IE6 */
_position: absolute;
_margin-top:0;
/* clientHeight:不包含邊匡的區塊高度( padding + height ) */
/* offsetHeight:包含邊匡的區塊高度( border + padding + height ) */
_top:expression(documentElement.scrollTop + ( documentElement.clientHeight-this.offsetHeight )/2
);
}
.fixed-top-center{
width:100px;
height:100px;
position:fixed;
top:0;
left:50%;
margin-left:-52px;
/* position fixed for IE6 */
_position: absolute;
_top:expression(documentElement.scrollTop);
}
.fixed-bottom-center{
width:100px;
height:100px;
position:fixed;
bottom:0;
left:50%;
margin-left:-52px;
/* position fixed for IE6 */
_position: absolute;
_top:expression( documentElement.scrollTop+documentElement.clientHeight-this.offsetHeight );
}
展示頁面(Demo Page)
參考來源:
上下左右置中、不隨頁面捲動的內容-小正正教室