1、定位定义
通过position属性指定了元素的定位类型,设置了该属性后能脱离文档流。
relative 相对定位
absolute 绝对定位
fixed 固定定位
它有四个方向进行位置调整:left top right bottom
2、相对定位
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>相对定位</title><style>.container{width: 300px;height: 300px;background-color:rebeccapurple;position: relative;left: 50px;top: 50px;}.box1{width: 100px;height: 100px;background-color:red;position: relative;left: 10px;top: 10px;}</style></head><body><div class="container"><div class="box1"></div></div></body></html>
效果如下,设置了相对定位或者绝对定位后,可以设置容器离left和top的距离像素,相对定位或者绝对定位是找具有定位元素的父级元素进行位置调整,如果父级元素不存在定位,则继续向上寻找,直到顶层。
3、绝对定位
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>绝对定位</title><style>.box1{width: 300px;height: 300px;background-color:rebeccapurple;position: absolute;left: 50px;top: 50px;}.box2{width: 300px;height: 300px;background-color:red;position: absolute;left: 100px;top: 100px;}.box3{width: 300px;height: 300px;background-color:blue;position: absolute;left: 150px;top: 150px;}</style></head><body><div class="box1"></div><div class="box2"></div><div class="box3"></div></body></html>
如下图,设置了几个绝对定位就会出现几层,层是可以叠加的。
与浮动不一样,浮动的元素都在一个同一个浮动层上不会出现叠加:
4、固定定位
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>固定定位</title><style>.box1{width: 100px;height: 300px;background-color:rebeccapurple;position: fixed;right: 0px;top: 500px;}.box2{height: 600px;}</style></head><body><div class="box1"></div><div class="box2"></div><div class="box2"></div><div class="box2"></div><div class="box2"></div><div class="box2"></div></body></html>
如下图,浮动层会固定在页面的某一个地方:
如淘宝固定的边栏:
