1. 定位
定位:将盒子指定到页面中的任意位置。
-
position
属性可以开启元素的定位
可选值:
static
没有开启定位(默认值)
relative
开启元素相对定位
absolute
开启元素的绝对定位
fixed
开启元素的固定定位
sticky
开启元素的粘性定位 -
开启定位后,通过
top right bottom left
四个属性设置元素的位置
2. 相对定位
- 相对于元素原来的位置进行定位
- 相对定位元素会提升一个层级
- 相对定位元素不会脱离文档流
- 相对定位元素不会改变元素的显示模式,(块还是块,行内还是行内)
- 元素移动后,原来的位置依然占用
3. 绝对定位
- 绝对定位会脱离文档流
- 绝对定位元素会改变元素的显示模式,具有行内块元素的特点
- 绝对定位参照开启了定位的祖先元素进行定位的
- 如果有没有祖先元素或者祖先元素没有开启定位,则以浏览器为参照进行定位
如果有开启了定位的祖先元素,则参照最近一级的祖先元素进行定位
4. 固定定位
- 固定定位会脱离文档流
- 固定定位会改变元素的显示模式,具有行内块元素的特点
- 固定定位参照浏览器的可视窗口进行定位
- 元素会固定在浏览器可视窗口的某个位置
5. 粘性定位(兼容性不好,IE不支持)
- 可以理解为相对定位和固定定位的结合
- 粘性定位不会脱离文档流
- 粘性定位参照浏览器可视窗口进行定位
- 粘性定位可以在元素到达某个位置时将其固定
示例如下:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>div {width: 200px;height: 200px;}.box1 {background-color: #c7edcc;/* 开启元素定位 *//* position: relative; *//* 移动元素位置 *//* left: 300px; *//* top: 300px; *//* 开启绝对定位 */position: absolute;/* 移动元素的位置 */left: 100px;top: 100px;}.box2 {background-color: #fde6e0;}/* .father {width: 300px;height: 300px;background-color: indianred;margin-top: 100px;margin-left: 200px; *//* 开启定位 *//* position: relative;} */.bbdbb {width: 500px;height: 500px;background-color: #dce2f1;/* 开启定位 */position: relative;}.box3 {background-color: #c7edcc;/* 开启固定定位 */position: fixed;/* 移动元素位置 *//* left: 100px;top: 100px; */right: 10px;bottom: 10px;}.box4 {background-color: #fde6e0;}.father {width: 300px;height: 300px;background-color: #dce2f1;margin-top: 100px;margin-left: 100px;position: relative;}body {height: 5000px;}.box5 {width: 1000px;height: 80px;background-color: #c7edcc;margin: 100px auto 0;/* 开启粘性定位 */position: sticky;/* 移动元素位置 */top: 10px;}
</head><body><!-- <div class="bbdbb"> --><!-- <div class="father"> --><!-- <div class="box1">我是div</div> --><!-- </div> --><!-- </div> --><!-- <div class="box2"></div> --><!-- <div class="father"><div class="box3">唔系渣渣辉,系兄弟就来砍我</div></div><div class="box4"></div> --><div class="box5"></div>
</body></html>