(四) css定位
一、为什么需要定位?
试想以下几种需求:
- 某个元素可以自由的在一个盒子内移动,并且压住其他盒子
- 当滚动窗口时,盒子是固定在屏幕某个位置的
- ......
这些效果,标准流或浮动都无法快速帮我们实现,此时就需要定位来实现
二、定位
所谓定位,就是将盒子定在某一个位置,所以定位的本质也是在摆盒子
2.1 定位的组成
定位 = 定位模式 + 边偏移
定位模式用于指定一个元素在文档中的定位方式。边偏移则决定了该元素的最终位置
定位模式:position 属性
值 | 语义 | 参照物 | 说明 |
static | 静态定位 | ||
relative | 相对定位 | 相对于自己原本的位置 | 保留原位置 |
absolute | 绝对定位 | 相对于祖先元素 | 脱离标准流 |
fixed | 固定定位 | 以浏览器的可视窗口 | 脱离标准流 |
边偏移
属性 | 描述 | 示例 |
top | 顶端偏移量,相对于父级上边线的距离 | top:10px |
bottom | 底部偏移量,相对于父级下边线的距离 | bottom:10px |
left | 左侧偏移量,相对于父级左边线的距离 | left:10px |
right | 右侧偏移量,相对于父级右边线的距离 | right:10px |
2.2 静态定位
静态定位是元素默认的定位方式,即:无定位
语法:选择器 { position:static; }
- 静态定位按照标准流特性摆放位置,没有边偏移
- 静态定位在布局时很少用到
2.3 相对定位(relative)
相对定位是相对于自己原来的位置移动的
语法:选择器 { position:relative; }
- 参照点是自己原来的位置
- 原来在标准流中的位置会继续保留,没有脱离标准流
因此使用相对定位的元素一般作为使用绝对定位元素的父亲
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box1 { /* 相对定位 */ position: relative; top: 100px; width: 80px; height: 20px; background-color: bisque; } .box2 { width: 80px; height: 20px; background-color: beige; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div> </body> </html>
2.4 绝对定位
绝对定位是以祖先元素为参照移动的
语法:选择器{ position:absolute; }
- 如果没有祖先元素 或 祖先元素没有定位,则以浏览器(Document文档)为参照
- 如果祖先有定位(相对、绝对、固定),则以最近一级有定位的祖先元素为参照
- 绝对定位的元素会脱离标准流
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box1 { position: absolute; width: 100px; height: 100px; background-color: antiquewhite; } .box2{ width: 200px; height: 100px; background-color: pink; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div> </body> </html>
2.5 子绝父相
“子绝父相”是定位中最常用的一种方式,即:子级是绝对定位的话,父级要用绝对定位
- 子级绝对定位,不会占有位置,可以放到父盒子的任何一个地方,不会影响其他兄弟盒子
- 父盒子要加定位限制子盒子在父盒子内显示
- 父盒子布局时,需要占有位置,因此父亲只能是相对定位
当然,子绝父相不是绝对的,如果父元素不需要占有位置,子绝父绝也会遇到
2.6 固定定位
固定定位是元素固定在浏览器的可视区域的位置。
语法:选择器 { position:fixed; }
- 以浏览器的可视窗口为参照移动位置
- 脱离标准流,不占有原来的位置
因此固定定位也可以看成是一种特殊的绝对定位
仅记录自己的学习总结,如有错误,还请评论指正~