目錄
- 1 參考文章
- 2 五個屬性值
- 3 position:static
- 4 position:relative(相對)
- 5 position:absolute(絕對)
1 參考文章
https://blog.csdn.net/lalala_dxf/article/details/123566909
https://blog.csdn.net/WangMinGirl/article/details/108648533
2 五個屬性值
position 屬性用來指定一個元素在網頁上的位置,一共有5種定位方式,也就是說 position 屬性主要有五個屬性值。如下:
屬性值 | 含義 |
---|---|
relative | 相對定位 |
absolute | 絕對定位 |
fixed | 固定定位 |
sticky | 粘性定位 |
3 position:static
- static 是 position 屬性的默認值。如果省略 position屬性,瀏覽器就認為該元素是 static定位。
- 瀏覽器會按照代碼的順序,決定每個元素的位置,這稱為"正常的文檔流"(normal flow)。每個塊級元素占據自己的區塊(block),元素與元素之間不產生重疊,這個位置就是元素的默認位置。
- static定位所導致的元素位置,是瀏覽器自主決定的,所以這時top、bottom、left、right、 z-index這五個屬性無效。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><link rel="stylesheet" href="./css/index.css" />
</head>
<body>bodybody<div class="box"><div class="same one">one</div><div class="same two">two</div><div class="same three">three</div></div>
</body>
</html>
.box{width:200px;border:5px solid black;
}
.box>.same{width:200px;height:200px;margin-bottom: 20px;text-align: center;
}.box>.one{background:#CCCCCC;
}
.box>.two{background:pink;
}
.box>.three{background:burlywood;
}
4 position:relative(相對)
偏移參考是元素本身原來的位置(static),不會使元素脫離文檔流。
搭配top、bottom、left、right這四個屬性使用,來設置偏移的方向和距離。left 和 right 不能一起設置,top 和 bottom 不能一起設置。不推薦和margin一起使用。
設置了相對定位的元素不管它是否進行移動,元素仍然占據它原來的位置。不會對其余內容進行調整來適應元素留下的任何空間。
移動元素可能會導致它覆蓋其他的元素。
相對定位元素常常作為絕對定位元素的父元素。
層級關系默認規則:定位元素會覆蓋在普通元素的上面;都設置定位的兩個元素,后寫的元素會覆蓋在先寫的元素上面。
在.box>.two增加
position: relative;
top: 40px;
left: 40px;
.box{width:200px;border:5px solid black;
}
.box>.same{width:200px;height:200px;margin-bottom: 20px;text-align: center;
}.box>.one{background:#CCCCCC;
}
.box>.two{background:pink;position: relative;top: 40px;left: 40px;
}
.box>.three{background:burlywood;
}
5 position:absolute(絕對)
默認以body節點作為參考點,如果祖先元素也是定位流(relative/absolute/fixed), 那么以定位流的祖先元素作為參考點。
絕對定位的元素會脫離普通流。
搭配top、bottom、left、right這四個屬性使用,left和right不能一起設置,top和bottom不能一起設置。不推薦和margin一起使用。
子絕父相:如果想要子元素定位于父元素的某個位置,子元素用絕對定位, 父元素用相對定位
.box>.two的position屬性改成 absolute;
.box{width:200px;border:5px solid black;
}
.box>.same{width:200px;height:200px;margin-bottom: 20px;text-align: center;
}.box>.one{background:#CCCCCC;
}
.box>.two{background:pink;position: absolute;top: 15px;left: 50px;
}
.box>.three{background:burlywood;
}
為.box>.two的祖先元素.box增加position: relative;屬性(子絕父相)
.box{width:200px;border:5px solid black;position: relative;
}
.box>.same{width:200px;height:200px;margin-bottom: 20px;text-align: center;
}.box>.one{background:#CCCCCC;
}
.box>.two{background:pink;position: absolute;top: 15px;left: 50px;
}
.box>.three{background:burlywood;
}