談css布局之position

position這個屬性定義建立元素布局所用的定位機制。
主要有以下幾個值:


static

所有元素在默認的情況下position屬性均為static,而我們在布局上經常會用到的相對定位和絕對定位常用的屬性top、bottom、left、right在position為static的情況下無效。
其用法為:在改變了元素的position屬性后可以將元素重置為static讓其回歸到頁面默認的普通流中。

<div style="border: solid 1px #0e0; width:200px;">
        <div style="height: 100px; width: 100px; background-color: Red;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Green;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Red;">
        </div>
    </div>

relative

relative 表現的和 static 一樣,除非你添加了一些額外的屬性。
在一個相對定位(position屬性的值為relative)的元素上設置 top 、 right 、 bottom 和 left 屬性會使其偏離其正常位置。其他的元素的位置則不會受該元素的影響發生位置改變來彌補它偏離后剩下的空隙。

<div style="border: solid 1px #0e0; width:200px;">
        <div style="height: 100px; width: 100px; background-color: Red;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Green; position:relative; top:20px; left:20px;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Red;">
        </div>
    </div>

absolute

absolute 與 fixed 的表現類似,但是它不是相對于視窗而是相對于最近的“positioned”祖先元素。如果絕對定位(position屬性的值為absolute)的元素沒有“positioned”祖先元素,那么它是相對于文檔的 body 元素,并且它會隨著頁面滾動而移動。
還是剛才的例子,讓綠色div絕對定位,為了清晰顯示,第二個紅色div改為黃色。

<div style="border: solid 1px #0e0; width:200px; position:relative;">
        <div style="height: 100px; width: 100px; background-color: Red;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Green; position:absolute; top:20px; left:20px;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Yellow;">
        </div>
    </div>

fixed

一個固定定位(position屬性的值為fixed)元素會相對于視窗來定位,即便頁面滾動,它還是會停留在相同的位置。和 relative 一樣, top 、 right 、 bottom 和 left 屬性都可用。

<div style="border: solid 1px #0e0; width:200px;">
        <div style="height: 100px; width: 100px; background-color: Red;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Green; position:fixed; bottom:20px; left:20px;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Yellow;">
        </div>
    </div>

所以說不管是頁面縱向滾動條在頁面頂端還是底端,綠色div總是在視口左下角。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容