一、absolute定位
absolute定位是相對於最近的帶有position定位的祖先元素進行定位的,如果沒有帶有position定位的祖先元素,則是相對於body元素進行定位。
例如,我們要將一個元素放置在頁面的右上角:
<html> <style> .box { width: 200px; height: 200px; background-color: yellow; position: absolute; // 添加定位屬性 top: 0; // 距離頁面頂部0px right: 0; // 距離頁面右側0px } </style> <body> <div class="box"></div> </body> </html>
這樣就可以將元素放置在右上角。
二、relative定位
relative定位是相對於元素本身原來的位置進行定位的,原來佔據的位置會被保留。
例如,我們想要將一個元素向下移動20px:
<html> <style> .box1 { width: 200px; height: 200px; background-color: yellow; } .box2 { width: 100px; height: 100px; background-color: red; position: relative; // 添加定位屬性 top: 20px; //向下移動20px } </style> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html>
根據上述代碼,我們創建了兩個不同的div元素,.box2添加了relative定位並移動了20px,但是原來的位置不會變化,.box1元素在頁面上保留了原始的位置.
三、fixed定位
fixed定位是相對於瀏覽器窗口進行定位的,當滾動頁面時,元素也不會移動。
例如,我們需要將一個元素始終固定在頁面右下角:
<html> <style> .box { width: 200px; height: 200px; background-color: yellow; position: fixed; //添加定位屬性 bottom: 0; //距離頁面底部0px right: 0; //距離頁面右側0px } </style> <body> <div class="box"></div> </body> </html>
現在,無論您如何滾動頁面,元素始終保留在右下角。
四、sticky定位
Sticky定位類似relative和fixed的混合體,當滾動到某個閾值時它變為fixed定位,這可以實現「黏性」效果。
例如,我們想要在頁面頂部添加一個黏性導航條:
<html> <style> nav { position: sticky; //添加定位屬性 top: 0; width: 100%; background-color: blue; color: white; padding: 20px; } section { height: 500px; } </style> <body> <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Contact</a></li> </ul> </nav> <section></section> </body> </html>
現在,當您滾動頁面時,導航條將「黏」在頂部,直到您到達頁面底部。
五、z-index屬性
z-index屬性規定了一個元素的堆疊順序,也就是說,哪一個元素位於另一個元素的前面或後面。
例如,我們創建兩個元素,一個具有更大的z-index值:
<html> <style> .box1 { width: 200px; height: 200px; background-color: yellow; position: absolute; top: 50px; left: 50px; z-index: 1; //添加z-index屬性 } .box2 { width: 200px; height: 200px; background-color: red; position: absolute; top: 100px; left: 100px; z-index: 2; //添加z-index屬性 } </style> <body> <div class="box1"></div> <div class="box2"></div> </body> </html>
在這個例子中,.box1元素具有更低的z-index值,.box2元素具有更高的z-index值,將其放在.box1元素的頂部。注意:更高的z-index值表示元素更接近屏幕的前景。
六、絕對定位與響應式布局的結合使用
使用響應式布局時,需要使用不同的CSS規則來解決頁面在不同設備上的顯示問題。在這種情況下,絕對定位非常有用。
例如,我們需要在大屏幕上和小屏幕上有不同的header布局:
<html> <style> @media screen and (min-width: 768px) { //媒體查詢:屏幕大於等於768px header { width: 100%; height: 100px; background-color: blue; position: absolute; top: 0; left: 0; z-index: 1; } main { position: relative; top: 100px; } } @media screen and (max-width: 767px) { //媒體查詢:屏幕小於768px header { width: 100%; height: 50px; background-color: red; position: absolute; top: 0; left: 0; z-index: 1; } main { position: relative; top: 50px; } } </style> <body> <header></header> <main></maim> </body> </html>
在這個例子中,通過@media查詢來檢測屏幕大小,如果屏幕大小大於等於768px,則.header元素是高100px,寬100%並且位於頁面頂部。在下面的元素中,主要內容在.header元素下面。如果屏幕大小小於768px,則.header元素具有較小的高度(50px),並且位置相同。.main元素有一個相對位置偏移,以使其避免與.header元素重疊。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/195610.html