武林網(wǎng)(www.survivalescaperooms.com)文章簡(jiǎn)介:CSS實(shí)現(xiàn)相對(duì)瀏覽器窗口定位徹底研究.
Web Developer / Designer 經(jīng)常需要將一個(gè)元素“固定”在頁面的某個(gè)位置。例如彈出窗口、漂浮廣告位等……本文將詳細(xì)介紹簡(jiǎn)單CSS實(shí)現(xiàn)元素相對(duì)于瀏覽器窗口進(jìn)行定位的方法。
position:fixed生成絕對(duì)定位的元素,相對(duì)于瀏覽器窗口進(jìn)行定位。元素的位置通過 “left”, “top”, “right” 以及 “bottom” 屬性進(jìn)行規(guī)定。
良好支持 W3C 標(biāo)準(zhǔn)的瀏覽器實(shí)例在 IE9、Firefox、Chrome等良好支持 W3C 標(biāo)準(zhǔn)的瀏覽器中,如果我們希望將某元素絕對(duì)定位于窗口正中間,我們可以給它指派這樣的 CSS樣式:
width:336px;height:280px;left:50%;top:50%;margin-left:-168px;margin-top:-140px;position:fixed;這里 margin-left 、margin-top 的值應(yīng)該修改為您頁面主要區(qū)域?qū)挾群透叨鹊囊话搿?/p>修正IE版本<7不支持position:fixed的bug
IE版本<7的瀏覽器不支持position:fixed屬性,所以并未實(shí)現(xiàn)期望的效果,這時(shí)就要針對(duì)IE<7的瀏覽器寫單獨(dú)的樣式。
(1)利用 Javascript 計(jì)算出需要的 top 值在head中插入:
<!--[if IE lt 7]><link rel="stylesheet" href="style.css" type="text/css" media="screen" /><![endif]-->在style.css樣式表中針對(duì)目標(biāo)定位元素樣式中寫入:
position:absolute;top:expression(eval(document.body.scrollTop + 50));防止?jié)L動(dòng)條滾動(dòng)時(shí)的閃動(dòng),需要定義HTMl的屬性為:
html {background-image: url(about: blank); /*用瀏覽器空白頁面作為背景*/background-attachment: fixed; /*確保滾動(dòng)條滾動(dòng)時(shí),元素不閃動(dòng)*/}在 IE 中特有的 CSS 運(yùn)算符 expression中我們可以利用 Javascript 計(jì)算出需要的 top 值,這樣就達(dá)到了與 position: fixed 同樣的效果。
(2)利用容器對(duì)溢出內(nèi)容的處理方式來實(shí)現(xiàn)定義body內(nèi)外邊距為0,實(shí)現(xiàn)html和瀏覽器窗口相同大小,使body出現(xiàn)滾動(dòng)條,元素相對(duì)于html相對(duì)定位。
body { padding: 0; margin: 0; }html { overflow: hidden; }body { height: 100%; overflow: auto; }針對(duì)IE6定義元素屬性:
position: absolute;top: 50% ;left: 50% ;margin-top: -140px;margin-left: -168px;讓元素固定于瀏覽器分別讓元素定位于瀏覽器左側(cè)、右側(cè)、頂部、底部綜合樣式演示:
position:absolute;bottom:auto;top:expression(eval(document.documentElement.scrollTop));/* IE6 頭部固定 */position:absolute;right:auto;left:expression(eval(document.documentElement.scrollLeft+document.documentElement.clientWidth-this.offsetWidth)-(parseInt(this.currentStyle.marginLeft, 10)||0)-(parseInt(this.currentStyle.marginRight, 10)||0));/* IE6 固定右側(cè) */position:absolute;bottom:auto;top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop, 10)||0)-(parseInt(this.currentStyle.marginBottom, 10)||0)));/* IE6 固定底部 */position:absolute;right:auto;left:expression(eval(document.documentElement.scrollLeft));/* IE6 左側(cè)固定 */新聞熱點(diǎn)
疑難解答
圖片精選