以往要達成這種模式的定位都要利用 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)
參考來源:上下左右置中、不隨頁面捲動的內容-小正正教室
4 回應:
您好! 請問一下~
在.fixed-top-center{}中
若是設"top: 20px",它好像還是置頂?!
有什麼方法可以解決呢?
謝謝~
不好意思 上一則留言沒有寫清楚
我的問題是指在ie6的狀態下。
謝謝~
IE6 的設定方式
_top:expression(documentElement.scrollTop+20);
補充一下,所有底線(_)開頭的樣式都是給IE6看的
張貼留言