在web前台開發時候,我們必不可少的會用到postion屬性進行布局定位。
今天總結了一下position知識點,與常用功能與大家分享,歡迎大家交流指正。
首先我們對postion屬性進行詳解。
在CSS3中,對於postion是這么描述的
總結如下:
static 是默認布局,設置top\left。。屬性不會有作用。
relative是相對布局,設置的top\left。。會相對文件中的控件。
absolute是絕對定位,設置的top\left。。會相對整個頁面而定。
fixed是相對瀏覽器窗口定位,設置的top/left屬性,是相對於瀏覽器窗口的位置。
除此之外,經過我代碼測試:
1.如果top\left。。其中某屬性缺省,absolute,fixed布局的位置,會相對於父控件的位置進行改變。
2.relative相對定位,如果有父控件,相對的是最近的一個父控件,而非同層最近的一個父控件。其次是兄弟控件。
3.static對其他的遮蓋層沒有影響。
接着我們來通過代碼證明以上結論:
情況1
HTML:
<div id="zero"> <div id="one">one</div> <div id="two">two</div> <div id="tree">tree</div> </div>
CSS:
#zero{ width:200px; height: 200px; margin: 100px 500px; background: black; z-index: 0; } #one{ width: 100px; height: 100px; position: relative; top: 50px; left:20px; background: red; z-index: 1; } #two{ width: 100px; height: 100px; position: absolute; top: 190px; background: yellow; z-index: 2; } #tree{ width: 100px; height: 100px; position: fixed; top: 250px; left: 600px; background: deepskyblue; z-index: 3; }
結果圖:
在此大家可以看出來id為one的div是相對父控件的布局。
情況2:
CSS:
#first{ width: 200px; height: 200px; background: black; margin-top: 100px; z-index: 1; } #second{ margin-top: 10px; margin-left:10px; width: 150px; height: 150px; background: yellow; z-index:2; } #thrid{ width: 100px; height: 100px; position:relative; background: red; top: 30px; left: 30px; z-index: 1; }
HTML:
<div id="first"> <div id="second"> <div id="thrid"></div> </div> </div>
效果圖:
從這里可以看出當relative定位是相對最近一個父控件的,而非同層父控件。
情況3:如果沒有父div:
HTML
<div id="out"></div> <div id="out1"></div>
CSS
#out{ margin-top: 50px; width: 200px; height: 200px; background: black; z-index: 1; } #out1{ width: 200px; height: 200px; background: yellow; position: relative; z-index: 3; top:10px; }
效果圖:
通過這種情況,看出來 如果沒有父控件,則relative定位是相對於兄弟關系的控件。
CSS3中對於z-index的描述
position開發中常見應用
1.網頁兩側浮動窗口(播放器,置頂按鈕,浮動廣告,功能按鈕等)
2.導航欄浮動置頂。
3.隱藏div實現彈窗功能(通過設置div的定位和z-index控制div的位置和出現隱藏)
其中1,3較為簡單,通過簡單的設置position=fixed,以及top left,z-index就能實現,此處不做說明
情況2:
通過調用js函數判斷滾動條所在的位置,超過導航欄距離頂部的高度時就設置position為fix固定導航欄位置,否則position為static,maring等屬性不變。
JS:
var mt = 0; window.onload = function () { var mydiv = document.getElementById("mydiv"); var mt = mydiv.offsetTop; window.onscroll = function () { var t = document.documentElement.scrollTop || document.body.scrollTop; if (t > mt) { mydiv.style.position = "fixed"; mydiv.style.margin = "0"; mydiv.style.top = "0"; } else { mydiv.style.margin = "30px 0"; mydiv.style.position = "static"; } } }
HTML:
<div class="nav auto mydiv" id="mydiv" style="z-index:2;"> <ul id="ulnav"> <li><a href="#">首頁</a></li> <li><a href="classes.html">班級設置</a></li> <li><a href="achievment.html" rel="nofollow" target="_blank">教學成果</a></li> <li><a href="techEnviroment.html" target="_blank">教學環境</a></li> <li><a href="specialCourse.html" target="_blank">特色課程</a></li> <li><a href="teacherTeam.html" target="_blank">教師團隊</a></li> <li><a href="contact.html" target="_blank">聯系方式</a></li> <li></li> </ul> </div>
設置合適的CSS控制自己想要的樣式。
效果圖: